System.Data.SqlClient Namespace
Represents a Transact-SQL statement or stored procedure to execute at an SQL Server™ database.
When an instance of SqlCommand is created, the read/write properties are set to their initial values. For a list of these values, see the SqlCommand constructor.
SqlCommand features the following methods to execute commands at an SQL Server™ database:
Item |
Description |
ExecuteReader |
Executes commands that return rows. For increased performance,
ExecuteReader invokes commands using the Transact-SQL sp_executesql
system stored procedure. As a result, ExecuteReader may not have the
desired effect if used to execute commands such as Transact-SQL SET
statements. |
ExecuteNonQuery |
Executes commands such as Transact-SQL INSERT, DELELE, UPDATE,
AND SET statements. |
ExecuteScalar |
Retrieves a single value ( for example, an aggregate value ) from
a database. |
ExecuteXmlReader |
Sends the CommandText to the Connection and builds an XmlReader object. |
If an SqlException is generated by the method executing an SqlCommand, the SqlConnection remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server usually closes the SqlConnection. However, the user can reopen the connection and continue.
The following example initializes an SqlConnection, an SqlCommand, and an SqlDataReader. The example reads through the data, writing it to the console. Finally, the example closes the SqlDataReader, then the SqlConnection.
void ReadMyData ( string connString ) {
string query = "SELECT OrderID, Customer FROM Orders";
SqlConnection myConn = new SqlConnection ( connString );
SqlCommand myCommand = new SqlCommand ( query, myConn );
myConn.Open ( );
SqlDataReader myReader = myCommand.ExecuteReader ( );
try {
while ( myReader.Read ( ) ) {
Response.Write ( myReader.GetInt32 ( 0 ) +
", " + myReader.GetString ( 1 ) );
}
}
finally {
// always close the reader when done.
myReader.Close ( );
// always close the connection when done.
myConn.Close ( );
}
}
Public Sub ReadMyData ( connString As String )
Dim query As String = "SELECT OrderID, Customer FROM Orders"
Dim myConn As New SqlConnection ( connString )
Dim myCommand As New SqlCommand ( query, myConn )
myConn.Open ( )
Dim myReader As SqlDataReader = myCommand.ExecuteReader ( )
Try
While myReader.Read ( )
Response.Write ( ( myReader.GetInt32 ( 0 ).ToString & _
", " & myReader.GetString ( 1 ) ) )
End While
Finally
' always close the reader when done.
myReader.Close ( )
' always close the connection when done.
myConn.Close ( )
End Try
End Sub |
|
C# |
VB |
SqlDataAdapter SqlConnection
|
|