Upload
ghardash
View
216
Download
0
Embed Size (px)
Citation preview
7/30/2019 Using the SQLCommand Object
1/9
Using the SQLCommand Object Page 1
Using the SQLCommand Object
In this article, you will learn how to use the .NET Framework Data Provider for DQL Server's SqlCommandobject to execute commands on a targetSQL Server system. It is taken from chapter 8 ofADO.NET: The Complete
Reference, written by Michael Otey and Denielle Otey (McGraw-Hill/Osborne, 2004; ISBN: 0072228989).
In this chapter, you see how to use the .NET Framework Data Provider forSQLServers SqlCommand object to
execute commands on a target SQL Server system. In the first part of this chapter, you learn how to execute
simple SQL action queries that dont return any values. Next, you see how to execute scalar queries using
both SQL statements and stored procedures that return single values. The chapter closes with a discussion of
how to use the SqlCommand object to commit and roll back transactions.
Executing SQL Statements and Stored Procedures Using the SqlCommand Object
Executing dynamic SQL statements and stored procedures are two of the most commondatabaseactions that are
required by an application. Dynamic SQL statements are SQL statements that are read by the database server
and executed when they are sent to the database server from the client application. When the database
receives these SQL statements, they are first parsed to ensure that their syntax is correct, and then the
database engine creates an access planessentially determining the best way to process the SQL statementandthen executes the statements. Unlike dynamic SQL statements, which are often used for executing SQL DML
operations like creating tables or for data access operations like performing ad hoc queries, stored
procedures are typically used to perform predefined queries and database update operations. Stored proceduresform the backbone of most database applications. The primary difference between dynamic SQL statements and
stored procedures is that stored procedures are typically created before the application is executed and they
reside in the database itself.
This gives stored procedures a significant performance advantage over dynamic SQL statements because the jobs
of parsing the SQL statement and creating the data access plan have already been completed. Its worth noting
that changes made to data contained in an ADO.NET DataSet either can be posted back to the database using
dynamic SQL statements created by the SqlCommandBuilder class, or can be written back to the database usingstored procedures. However, you dont need to use the DataSet and DataAdapter in order to update the
database. In cases where you dont need the data binding and navigation functions provided by the DataSet,
the Command objects can provide a much lighter-weight and more-efficient method of updating the database. In
the next sections, youll see how to use the SqlCommand object to execute an ad hoc query, and then to
execute a SQL DDL statement to build a table on the target database, followed by two examples using thestored procedure. The first stored procedure example illustrates passing parameters to a stored procedure,
and the second example illustrates executing a stored procedure that supplies a return value.
Using the Visual Studio SqlCommand Object
The easiest place to get started with the SqlCommand object is probably using the visual component providedas a part of Visual Studio.NET. Using the same drag-and-drop paradigm thats implemented for interfacecomponents, you can drag and drop an instance of the SqlCommand from the Visual Studio.NET DataToolbox onto
the visual designer. After youve done this, youll see a new SqlCommand object in the components pane, as
shown in Figure 8-1.
Figure 8-1.Adding the Visual SqlCommand object to a Visual Studio.NET project
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/7/30/2019 Using the SQLCommand Object
2/9
Using the SQLCommand Object Page 2
Dragging and dropping the SqlCommand component from the Data tab to the Design window results in the creationof the SqlCommand1 object that is displayed in the component window at the bottom of the screen. After that,the SqCommand1 component is ready to use. The follow example illustrates executing a simple ad hoc query with
the visual SqlCommand component:
private void SQLCommandComponent(string sServer, string sDB){
sqlConnection1.ConnectionString = "SERVER=" + sServer + ";"+ "INTEGRATED SECURITY=True;DATABASE=" + sDB;
sqlCommand1.CommandText = "SELECT * FROM customers";
// Set the active connectionsqlCommand1.Connection = sqlConnection1;try{
// Open a connectionsqlConnection1.Open();// Execute the querysystem.Data.SqlClient.SqlDataReader dr =
sqlCommand1.ExecuteReader();// The reader can now be processed
}catch (Exception ex)
{MessageBox.Show(ex.Message);
}sqlConnection1.Close();
}
At the top of the SQLCommandComponent routine, you can see where two variables are passed in as parameters.
The sServer variable contains the name of the SQL Server system that will be the database server; the sDB
variable contains the name of the database that will be accessed. These examples all use the Northwinddatabase that's supplied as a sample database with SQL Server.
The first action within the routine sets the SqlConnection1 objects connection string using the server and
database values that were passed into the routine. The Integrated Security keyword indicates that Windows
authentication will be used for the connection. You should note that even though this example is using the
visual SqlCommand component, it still requires a SqlConnection object to actually connect to the targetdatabase. Although this example uses the visual SqlConnection1 object, this could also use a code-based
SqlConnection object as well.
Next the CommandText property of the SqlCommand1 object is assigned a simple SQL SELECT statement that will
query all of the rows and columns from the Customers table found in the Northwind database. The nextstatement sets the Sql1Command1 objects Connection property to the SqlConnect1 object. Then a Try-Catch
block is set up to open the connection and execute the command. The SqlConnection1.Open method is used to
initiate a connection to the targetSQL Serversystem; then the SqlCommand1 objects ExecuteReader command is
used to create a SqlDataReader object named dr. The ExecuteReader method is used to return a fast forward-
only data stream from the target data source. Table 8-1 lists all of the different SQL command executionmethods supported by both the SqlCommand object and the OleDbCommand object.
After the ExecuteReader method has completed, the results of the query can then be accessed using the dr
SqlDataReader object. The detailed usage of the SqlDataReader will be presented in the next chapter. If an
error occurs during the execution of either the Open method or the ExecuteReader, a message box will be
displayed to the user showing the exception text.
Method Description
ExecuteNonQuery The ExecuteNonQuery method is used to execute a SQL statement on the connected datasource. It is used for DDL statements and action queries like insert, update, andDelete operations, as well as ad hoc queries. The number of rows affected is returned,
but no output parameters or resultsets are returned.
ExecuteReader The ExecuteReader method is used to execute a SQL Select statement on the data source.A fast forward-only result is returned. More examples of the ExecuteReader method areshown in Chapter 6.
ExecuteScalar The ExecuteScalar method is used to execute a stored procedure or a SQL statement that
returns a single scalar value. The first row of the first column of the resultset is
returned to the calling application. Any other returned values are ignored.
ExecuteXMLReader The ExecuteXMLReader method is used to execute a FOR XML SELECT statement that returnsan XML data stream from the data source. More examples of the ExecuteXMLReader method
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/7/30/2019 Using the SQLCommand Object
3/9
Using the SQLCommand Object Page 3
are shown in Chapter 30. The ExecuteXMLReader command is compatible only with SQL
Server 2000 and later.
Table 8-1. SqlCommand SQL Statement Execution Methods
Using the SQLCommand Object - Adding the System.Data.SqlClient Namespace
Although using the visual connection components provided by theVisual Studio.NET design environment is
pretty easy, in the long run, youll probably find it simpler to use the ADO.NET objects by just writingcode. To use the SqlCommand class in your project, you first need to add an import directive for the
System.Data.SqlClient Namespace in your project. The following example illustrates how to do this for a C#project:
using System.Data.SqlClient;
After the import directive has been added, youre ready to use code-based SqlCommand objects in your
projects.
Executing Dynamic SQL Statements Using SqlCommand
DynamicSQLprovides an extremely flexible mechanism for working with the database. Dynamic SQL allows you to
execute ad hoc queries and return the results from action queries, as well as execute SQL DDL statements to
create database objects. The following SQLCommandNonQuery subroutine provides an example illustrating how you
can use dynamic SQL with the ADO.NET SqlCommand object to check for the existence of a table andconditionally create it if it doesnt exist:
private void SQLCommandNonQuery(string sServer, string sDB){
SqlConnection cn = new SqlConnection("SERVER=" + sServer+ ";INTEGRATED SECURITY=True;DATABASE=" + sDB);
string sSQL;SqlCommand cmd = new SqlCommand("", cn);
try{
// Open the connectioncn.Open();// First drop the tablesSQL = "IF EXISTS "
+ "(SELECT * FROM dbo.sysobjects "+ "WHERE id = object_id(N'[Department]') "+ "AND OBJECTPROPERTY(id, N'IsUserTable') = 1) "
+ "DROP TABLE [department]";cmd.CommandText = sSQL;cmd.ExecuteNonQuery();// Then create the tablesSQL = "CREATE TABLE Department "
+ "(DepartmentID Int NOT NULL, "+ "DepartmentName Char(25), "+ "PRIMARY KEY(DepartmentID))";
cmd.CommandText = sSQL;cmd.ExecuteNonQuery();
}catch(Exception ex){
MessageBox.Show(ex.Message);}// Close the connection
cn.Close();}
In the first part of the SQLCommandNonQuery subroutine, you can see where the sServer and sDB variables are
passed as parameters. The values of these two variables are used to specify theSQL Serverdatabase server
and database that will be used. Next, a new SqlConnection object named cn is created. In this example, theconnection string is passed in as the first parameter of the SqlConnection objects constructor. The
connection string uses Integrated Security to connect to the server and database specified using the server
and database keywords. For more information about the Sql Connection objects connection string keywords, youcan refer to Chapter 4.
After the Connection object has been created, the sSQL variable that will be used to contain the dynamic SQL
statements and an instance of the SqlCommand object named cmd are instantiated. In this example, the
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/7/30/2019 Using the SQLCommand Object
4/9
Using the SQLCommand Object Page 4
constructor of the cmd SqlCommand object uses two parametersthe first being a string containing the SQL
statement that will be executed, and the second being the SqlConnection object that will provide theconnection to the target database server. Here the sSQL string is initially empty. Next, a Try-Catchstructure is set up to execute the SQL commands. The first action that you can see within the Try-Catch block
uses the cn SqlConnection objects Open method to open a connection to the SQL Server database that was
specified earlier in the connection string used in the SqlConnection objects constructor. Then, the sSQL
variable is assigned a SQL statement that checks for the existence of the department table. In this SQL
statement, you can see that a Select statement queries the SQL Server sysobjects table to determine if a User
Table named Department exists.
If the Department table is found, a DROP TABLE statement will be executed to remove the table from the target
database. Otherwise, if the Department table isnt found, no further action will be taken. In order to
actually execute the SQL statement, that value in the sSQL variable is then assigned to the CommandText
property of the cmd object, and then the ExcuteNonQuery method of the cmd SqlCommand object is used to sendthe command to theSQL Server system. The ExecuteNonQuery method is used to execute a SQL statement that
doesnt return a resultset or a specific return value.
After the first DROP TABLE SQL command has been issued, the same sequence is followed to execute a Create
Table command. First, the sSQL variable is assigned a SQL CREATE TABLE statement that creates a table named
Department that consists of two columns. The first column is an integer data type named DepartmentID, whichis also the primary key, and the second column is a 25-character data type named DepartmentName. Then the
value in the sSQL variable is copied to the cmd objects CommandText property, and the ExecuteNonQuery method
is called to execute the CREATE TABLE SQL statement. Following the successful completion of theExecuteNonQuery method, the Department Table will exist in the database that was earlier identified in the
sDB variable.
If an error occurs during any of these operations, the SqlConnection objects Open method or either instance
of the SqlCommand objects ExecuteNonQuery method, then the code in the Catch block will be executed, and a
message box will be displayed showing the text of the exception condition.
At the end of the CommandNonQuery subroutine, the SqlConnection objects Close method is executed to end the
connection to the SQL Server database.
Using the SQLCommand Object - Executing Parameterized SQL Statements
In addition to executing dynamic SQLstatements, the SqlCommand object can also be used to execute storedprocedures and parameterized SQL statements. The primary difference between dynamic SQL and prepared SQL is
that dynamic SQL statements must be parsed and an access plan must be created before each run. (Technically,
some database systems like SQL Server are very smart about the way this is handled, and they will actually
store dynamic statements for a period of time. Then when the statement is subsequently executed, the existing
access plan will be used. Even so, this depends on the database activity; and with dynamic SQL, theres no
guarantee that the plan will be immediately available.) You can think of prepared SQL statements as sort of across between stored procedures and dynamic SQL. Like stored procedures, they can accept different parametervalues at runtime. Like dynamic SQL, they are not persistent in the database. The SQL statement is parsed and
the access plan is created when the application executes the SQL statements. However, unlike dynamic SQL, the
prepared SQL is parsed and the access plan is only created once when the statement is first prepared.
Subsequent statement execution takes advantage of the existing access plan. The access plan will typically
remain in the procedure cache until the connection is terminated. The following example shows how to createand execute a prepared SQL statement using the ADO.NET SqlCommand object:
private void SQLCommandPreparedSQL(string sServer, string sDB){
SqlConnection cn = new SqlConnection("SERVER=" + sServer+ ";INTEGRATEDSECURITY=True;DATABASE=" + sDB);
//Set up the Command object's parameter typesSqlCommand cmd = new SqlCommand("INSERT INTO department VALUES"
+ "(@DepartmentID, @DepartmentName)", cn);SqlParameter parmDepartmentID =
new SqlParameter("@DepartmentID", SqlDbType.Int);parmDepartmentID.Direction = ParameterDirection.Input;SqlParameter parmDepartmentName =
new SqlParameter("@DepartmentName", SqlDbType.Char, 25);parmDepartmentName.Direction = ParameterDirection.Input;// Add the parameter objects to the cmd Parameter's collection
cmd.Parameters.Add(parmDepartmentID);cmd.Parameters.Add(parmDepartmentName);try
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/7/30/2019 Using the SQLCommand Object
5/9
Using the SQLCommand Object Page 5
{// Open the connection & prepare the commandcn.Open();cmd.Prepare();// Execute the prepared SQL statement to insert 10 rowsfor (int i = 1; i
7/30/2019 Using the SQLCommand Object
6/9
Using the SQLCommand Object Page 6
SmallMoney Decimal
Text String
Timestamp DateTime
TinyInt Byte
UniqueIdentifier GuidVarBinary Array of type Byte
VarChar String
Variant Object
Table 8-2. DbType Enumerations
Enumeration Description
ParameterDirection.Input The parameter is an input parameter.
ParameterDirection.InputOutput The parameter is capable of both input and output.
ParameterDirection.Output The parameter is an output parameter.
ParameterDirection.ReturnValue The parameter represents a return value.
Table 8-3. SqlParameterDirection Enumeration
After the SqlParameter objects have been created, the next step is to add them to the SqlCommand objects
Parameters collection. In the previous listings, you can see that you use the Add method of the SqlCommand
objects Parameters collection to add both the parmDepartmentID and parmDepartmentName SqlParameter objectsto the cmd SqlCommand object. The order in which you add the SqlParameter objects isnt important. Next,
within the Try-Catch block, the cn SqlConnection objects Open method is used to open a connection toSQL
Server and then the Prepare statement is used to prepare the statement. Note that the Prepare method isexecuted after all of the parameter attributes have been described.
NOTE Using the Prepare operation provides an important performance benefit for parameterized queries because
it instructs SQL Server to issue an sp_prepare statement, thereby ensuring that the statement will be in the
Procedure cache until the statement handle is closed.
Next, a For-Next loop is used to add 10 rows to the newly created Department table. Within the For-Next loop,
the Value property of each parameter object is assigned a new data value. For simplicity, theparmDepartmentID parameter is assigned the value of the loop counter contained in the variable i while the
parmDepartmentName parameter is assigned a string containing the literal "New Department" along with the
current value of the loop counter. Last, the SqlCommand objects ExecuteNonQuery method is used to execute
the SQL statement. In this case, ExecuteNonQuery was used because this example is using a SQL action query
that doesnt return any values. From the SQL Server perspective, running the ExecuteNonQuery method resultsin the server issuing an sp_execute command to actually perform the insert.
NOTE If you need to pass a null value as a parameter, you need to set the parameter to the value
DBNull.Value.
If an error occurs during any of these operations, the code in the Catch block will be executed and a messagebox will be displayed showing the text of the exception condition.
At the end of the subroutine, the SqlConnection objects Close method is executed to end the connection to
the SQL Server database.
Using the SQLCommand Object - Executing Stored Procedures with Return Values
Stored procedures are the core of most database applicationsand for good reason. In addition to their
performance benefits, stored procedures can also be a mechanism for restricting data access to the predefinedinterfaces that are exposed by the stored procedures. Similar to preparedSQLstatements, stored procedures
get significant performance benefits from the fact that they are compiled before they are used. This allows
the database to forego the typical parsing steps that are required, skipping the need to create an accessplan. Stored procedures are the true workhorse of most database applications, and they are almost always used
for database insert, update, and delete operations, as well as for retrieving single values and result sets.
In the following examples, you see how to execute SQL Server stored procedures using the SqlCommand object.
In the first example that follows, youll see how to execute a stored procedure that accepts a single input
parameter and returns a scalar value.
The following listing presents the T-SQL source code required to create the StockValue stored procedure that
will be added to the sample Northwinddatabase. You can create this stored procedure by executing this code
using Query Analyzer.
CREATE PROCEDURE StockValue@ProductID int
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/7/30/2019 Using the SQLCommand Object
7/9
Using the SQLCommand Object Page 7
ASDECLARE @StockValuemoneySELECT StockValue = (UnitsInStock * UnitPrice)FROM Products WHERE ProductID = @ProductIDRETURN @StockValue
In the preceding listing, you can see that the StockValue stored procedure accepts a single input parameter.That parameter is an Integer value thats used to identify the ProductID. The StockValue stored procedure
returns the stock value of that ProductID from the Products table in the Northwind database. The stock value
is calculated by retrieving the UnitsInStock number and multiplying it by the value in the UnitPrice column.The results are then assigned to the @StockValue variable, which is returned as a scalar value by the stored
procedure. After the sample stored procedure has been created in the Northwind database, it can be called byyour ADO.NET applications. The following example shows how to use the SQLCommand class form VB.NET to executethe StockValue stored procedure and retrieve the scalar value that it returns:
private void SQLCommandPSScalar(string sServer, string sDB)
{SqlConnection cn = new SqlConnection("SERVER=" + sServer
+ ";INTEGRATED SECURITY=True;DATABASE=" + sDB);// Create the command object and set the SQL statementSqlCommand cmd = new SqlCommand("StockValue", cn);cmd.CommandType = CommandType.StoredProcedure;// Create the parametercmd.Parameters.Add("@ProductID", SqlDbType.Int);cmd.Parameters["@ProductID"].Direction =
ParameterDirection.Input;cmd.Parameters["@ProductID"].Value = 1;
try{
decimal nStockValue;// Open the connection and execute the commandcn.Open();nStockValue = (decimal)cmd.ExecuteScalar();
txtMid.Text = nStockValue.ToString();}catch (Exception ex){
MessageBox.Show(ex.Message);}// Close the connectioncn.Close();
}
In the beginning of this routine you can see where the cn SqlConnection object is created, followed by thecreation of the SqlCommand object named cmd. In this example, the constructor for the SqlCommand object uses
two parameters. The first parameter is a string that accepts the command that will be executed. This can beeither a SQL statement or the name of the stored procedure. In this example, you can see that the name of the
StockValue stored procedure is used. The second parameter is used for the name of the SqlConnection object
that will be used to connect to the target database. After the cmd SqlCommand object has been created, its
CommandType property is set to CommandType.StoredProcedure indicating that a stored procedure will beexecuted. The CommandType property can accept any of the values shown in the following table:
CommandType Values Description
CommandType.StoredProcedure The command is a stored procedure.
CommandType.TableDirect The command is the name of a database table.CommandType.Text The command is a SQL statement.
After the SqlCommand objects CommandType property is set to CommandType.StoredProcedure, the SqlParameterobject used to supply the input value to the StockValue stored procedure is created. SqlParameter objects can
be created either by using the SqlParameter class constructor or by executing the SqlCommand objects
Parameters collection Add method. In this example, the parameter is created using the Add method of the
SqlCommand objects Parameters collection. The first parameter supplied to the Add method is a string
containing the name of the parameter. In this case "@ProductID".
Again, note that replaceable parameters used by the SQLParameter object must begin with the at symbol (@).
The second parameter uses the SqlDbType.Int enumeration to indicate that the parameter will contain an
Integer value. The next line sets the Direction property to the value ParameterDirection.Input to indicate
that this is an input parameter. Last, the SqlParameter objects Value property is set to 1 storing a valueof 1 to pass to the StockValue stored procedure.
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/7/30/2019 Using the SQLCommand Object
8/9
Using the SQLCommand Object Page 8
The next section of code sets up a Try-Catch block to open the connection to theSQL Serversystem and then
executes the StockValue stored procedure. The important point to note in the Try-Catch block is that the cmdSqlCommand objects ExecuteScalar method is used to execute the StockValue stored procedure and the returnvalue is assigned to the nStockValue variable. The contents of the nStockValue variable are then assigned to
a text box. Like the earlier examples, if the connection or the stored procedure fails, a message box showing
the error text will be displayed to the end user. Then the connection will be closed.
Using the SQLCommand Object - Executing Transactions
Transactions enable you to group together multiple operations that can be performed as a single unit of work,
which helps to ensuredatabaseintegrity. For instance, transferring funds from your savings account to your
checking account involves multiple database operations, and the transfer cannot be considered complete unless
all of the operations are successfully completed. A typical transfer from your savings account to your
checking account requires two separate but related operations: a withdrawal from your savings account and adeposit to your checking account. If either operation fails, the transfer is not completed. Therefore, bothof these functions would be considered part of the same logical transaction. From the database standpoint, to
ensure database integrity, both the withdrawal and the deposit would be grouped together as a single
transaction. If the withdrawal operation succeeded but the deposit failed, the entire transaction could be
rolled back, which would restore the database to the condition it had before the withdrawal operation was
attempted. Using transactions is an essential part of most production-level database applications.
ADO.NET supports transactions using the Transaction classes. In order to incorporate transactions into your
ADO.NET application you first need to create an instance of the SqlTransaction object and then execute theBeginTransaction method to mark the beginning of a transaction. Under the covers this will cause the database
server to begin a transaction. For instance, using the SqlTransaction object to issue a BeginTransaction
statement will send a T-SQL BEGIN TRANSACTION command toSQLServer. After the transaction has started, thedatabase update operations are performed and then the Commit method is used to actually write the updates to
the target database. If an error occurs during the process, then the RollBack operation is used to undo the
changes. The following SQLCommandTransaction subroutine shows how to start a transaction and then eithercommit the results of the transaction to the database or roll back the transaction in the event of an error:
private void SQLCommandTransaction(string sServer, string sDB){
SqlConnection cn = new SqlConnection("SERVER=" + sServer
+ ";INTEGRATED SECURITY=True;DATABASE=" + sDB);SqlCommand cmd = new SqlCommand();SqlTransaction trans;// Start a local transactioncn.Open();trans = cn.BeginTransaction();cmd.Connection = cn;
cmd.Transaction = trans;try{
// Insert a row transactioncmd.CommandText =
"INSERT INTO Department VALUES(100, 'Transaction 100')";cmd.ExecuteNonQuery();// This will result in an errorcmd.CommandText =
"INSERT INTO Department VALUES(100, 'Transaction 101')";
cmd.ExecuteNonQuery();trans.Commit();
}catch (Exception ex){
MessageBox.Show(ex.Message);
trans.Rollback();}finally{
cn.Close();}
}
In the beginning of this subroutine, you can see where new instances of the SqlConnection and SqlCommand
objects are created, followed by the definition of a SqlTransaction object named trans. Next, a local
transaction is started by first opening the connection and then using the cn SqlConnection objects
BeginTransaction method to create a new instance of a SqlTransaction object. Note that the connection must be
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/7/30/2019 Using the SQLCommand Object
9/9
Using the SQLCommand Object Page 9
open before you execute the BeginTransaction method. Next, the cmd SqlCommand Connection property is assigned
with the cn SqlConnection and the Transaction property is assigned with the trans SqlTransaction object.Within the Try-Catch block, two commands are issued that are within the local transaction scope. The firstcommand is an INSERT statement that inserts two columns into the Department table that was created previously
in this chapter. The first insert statement adds the DepartmentID of 100 along with a DepartmentName value of
'Transaction 100'. The SqlCommand ExecuteNonQuery method is then used to execute the SQL statement. Next, the
cmd objects CommandText property is set to another SQL INSERT statement. However, this statement will cause
an error because it is attempting to insert a duplicate primary key value. In this second case, the
DepartmentID of 100 is attempted to be inserted along with the DepartmentName value of 'Transaction 101'.This causes an error because the DepartmentID of 100 was just inserted by the previous INSERT statement. When
the ExecuteNonQuery method is executed, the duplicate primary key error will be issued and the code in the
Catch portion of the Try-Catch block will be executed.
Displaying the exception message in a message box is the first action that happens within the Catch block.You can see an example of this message in Figure 8-2.
Figure 8-2.A duplicate primary key error prevents the Commit operation.
After the message box is displayed, the trans SqlTransaction objects RollBack method is used to roll back
the attempted transaction. Note that because both insert statements were within the same transaction scopeboth insert operations will be rolled back. The resulting department table will not contain eitherDepartmentID 100 or DepartmentID 101.
In this example, a Finally block is used to close the cn SqlConnection object. If the Finally block is
attached to the Try-Catch structure, the code in the Finally block will always be executed.
SummaryIn this chapter, you saw several examples illustrating how to execute commands using the .NET FrameworkData
Provider for SQL Servers SqlCommand object. The examples in the first part of the chapter illustrated how touse the SqlCommand object to execute SQL statements and stored procedures. In the second part of the chapter,
you learned how to use transactions. The next chapter begins where this chapter leaves off: youll see how to
execute commands using the OracleCommand object.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. Thecontent provided is intended for entertainment and/or educational purposes in order to introduce to the
reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative
consequences that may result from implementing any information covered in our articles or tutorials. If this
is ahardwarereview, it is not recommended to open and/or modify your hardware.
http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/http://www.aspfree.com/