Tải bản đầy đủ - 0 (trang)
9-6. Use Parameters in a SQL Command or Stored Procedure

9-6. Use Parameters in a SQL Command or Stored Procedure

Tải bản đầy đủ - 0trang

CHAPTER 9 ■ DATABASE ACCESS



value of each parameter is substituted into the command string before the command is executed against

the data source. You can create parameter objects in the following ways:





Use the IDbCommand.CreateParameter method.







Use the IDbCommand.Parameters.Add method.







Use System.Data.Common.DbProviderFactory.







Directly create parameter objects using constructors and configure them using

constructor arguments or through setting their properties. (This approach ties you

to a specific database provider.)



A parameter object’s properties describe everything about a parameter that the command object

needs to use the parameter object when executing a command against a data source. Table 9-4 describes

the properties that you will use most frequently when configuring parameters.

Table 9-4. Commonly Used Parameter Properties



Property



Description



DbType



A value of the System.Data.DbType enumeration that specifies the type of data

contained in the parameter. Commonly used values include String, Int32, DateTime,

and Currency.



Direction



A value from the System.Data.ParameterDirection enumeration that indicates the

direction in which the parameter is used to pass data. Valid values are Input,

InputOutput, Output, and ReturnValue.



IsNullable



A bool that indicates whether the parameter accepts null values.



ParameterName



A string containing the name of the parameter.



Value



An object containing the value of the parameter.



When using parameters to execute stored procedures, you must provide parameter objects to satisfy

each argument required by the stored procedure, including both input and output arguments. You must

set the Direction property of each parameter as described in Table 9-4; parameters are Input by default.

If a stored procedure has a return value, the parameter to hold the return value (with a Direction

property equal to ReturnValue) must be the first parameter added to the parameter collection.



The Code

The following example demonstrates the use of parameters in SQL commands. The

ParameterizedCommandExample method demonstrates the use of parameters in a SQL Server UPDATE

statement. The ParameterizedCommandExample method’s arguments include an open SqlConnection and

two strings. The values of the two strings are substituted into the UPDATE command using parameters.

The StoredProcedureExample method demonstrates the use of parameters to call a stored procedure.



442



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



using System;

using System.Data;

using System.Data.SqlClient;

namespace Apress.VisualCSharpRecipes.Chapter09

{

class Recipe09_06

{

public static void ParameterizedCommandExample(SqlConnection con,

string employeeID, string title)

{

// Create and configure a new command containing two named parameters.

using (SqlCommand com = con.CreateCommand())

{

com.CommandType = CommandType.Text;

com.CommandText = "UPDATE Employees SET Title = @title" +

" WHERE EmployeeId = @id";

// Create a SqlParameter object for the title parameter.

SqlParameter p1 = com.CreateParameter();

p1.ParameterName = "@title";

p1.SqlDbType = SqlDbType.VarChar;

p1.Value = title;

com.Parameters.Add(p1);

// Use a shorthand syntax to add the id parameter.

com.Parameters.Add("@id", SqlDbType.Int).Value = employeeID;

// Execute the command and process the result.

int result = com.ExecuteNonQuery();

if (result == 1)

{

Console.WriteLine("Employee {0} title updated to {1}.",

employeeID, title);

}

else

{

Console.WriteLine("Employee {0} title not updated.",

employeeID);

}

}

}

public static void StoredProcedureExample(SqlConnection con,

string category, string year)

{



443



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Create and configure a new command.

using (SqlCommand com = con.CreateCommand())

{

com.CommandType = CommandType.StoredProcedure;

com.CommandText = "SalesByCategory";

// Create a SqlParameter object for the category parameter.

com.Parameters.Add("@CategoryName", SqlDbType.NVarChar).Value =

category;

// Create a SqlParameter object for the year parameter.

com.Parameters.Add("@OrdYear", SqlDbType.NVarChar).Value = year;

// Execute the command and process the results.

using (IDataReader reader = com.ExecuteReader())

{

Console.WriteLine("Sales By Category ({0}).", year);

while (reader.Read())

{

// Display the product details.

Console.WriteLine(" {0} = {1}",

reader["ProductName"],

reader["TotalPurchase"]);

}

}

}

}

public static void Main()

{

// Create a new SqlConnection object.

using (SqlConnection con = new SqlConnection())

{

// Configure the SqlConnection object's connection string.

con.ConnectionString = @"Data Source = .\sqlexpress;" +

"Database = Northwind; Integrated Security=SSPI";

// Open the database connection and execute the example

// commands through the connection.

con.Open();

ParameterizedCommandExample(con, "5", "Cleaner");

Console.WriteLine(Environment.NewLine);

StoredProcedureExample(con, "Seafood", "1999");

Console.WriteLine(Environment.NewLine);

}



444



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



9-7. Process the Results of a SQL Query Using a Data Reader

Problem

You need to process the data contained in a System.Data.IDataReader instance returned when you

execute the IDbCommand.ExecuteReader method (discussed in recipe 9-5).



Solution

Use the members of the IDataReader instance to move through the rows in the result set sequentially

and access the individual data items contained in each row.



How It Works

The IDataReader interface represents a data reader, which is a forward-only, read-only mechanism for

accessing the results of a SQL query. Each data provider includes a unique IDataReader implementation.

Here is the list of IDataReader implementations for the five standard data providers:





System.Data.Odbc.OdbcDataReader







System.Data.OleDb.OleDbDataReader







System.Data.OracleClient.OracleDataReader







System.Data.SqlServerCe.SqlCeDataReader







System.Data.SqlClient.SqlDataReader



The IDataReader interface extends the System.Data.IDataRecord interface. Together, these

interfaces declare the functionality that provides access to both the data and the structure of the data

contained in the result set. Table 9-5 describes some of the commonly used members of the IDataReader

and IDataRecord interfaces.



445



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



Table 9-5. Commonly Used Members of Data Reader Classes



Member



Description



Property

FieldCount



Gets the number of columns in the current row.



IsClosed



Returns true if IDataReader is closed, and false if it’s currently open.



Item



Returns an object representing the value of the specified column in the current row.

Columns can be specified using a zero-based integer index or a string containing the

column name. You must cast the returned value to the appropriate type. This is the

indexer for data record and reader classes.



Method

GetDataTypeName



Gets the name of the data source data type for a specified column.



GetFieldType



Gets a System.Type instance representing the data type of the value contained in the

column specified using a zero-based integer index.



GetName



Gets the name of the column specified by using a zero-based integer index.



GetOrdinal



Gets the zero-based column ordinal for the column with the specified name.



GetSchemaTable



Returns a System.Data.DataTable instance that contains metadata describing the

columns contained in IDataReader.



IsDBNull



Returns true if the value in the specified column contains a data source null value;

otherwise, it returns false.



NextResult



Moves to the next set of results if IDataReader includes multiple result sets because

multiple statements were executed. By default, IDataReader is positioned on the first

result set.



Read



Advances the reader to the next record. The reader always starts prior to the first

record.



In addition to those members listed in Table 9-5, the data reader provides a set of methods for

retrieving typed data from the current row. Each of the following methods takes an integer argument

that identifies the zero-based index of the column from which the data should be returned: GetBoolean,

GetByte, GetBytes, GetChar, GetChars, GetDateTime, GetDecimal, GetDouble, GetFloat, GetGuid, GetInt16,

GetInt32, GetInt64, GetString, GetValue, and GetValues.

The SQL Server and Oracle data readers also include methods for retrieving data as data source–

specific data types. For example, SqlDataReader includes methods such as GetSqlByte, GetSqlDecimal,



446



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

9-6. Use Parameters in a SQL Command or Stored Procedure

Tải bản đầy đủ ngay(0 tr)

×