How to use the SqlCommand object
In this snippet:
- How to create a SqlConnection
object
- How to create a SqlCommand
object
- How to create a SqlDataReader
object
- How to read data from a SQL Server table using the
ExecuteReader
method.
- How to write data from a SqlDataReader
to
the Console
- How to close a SqlDataReader
object
- How to close a SqlConnection
object
First a connection is opened. Then, using a SqlCommand
object it selects a set of rows from a table and writes
them to the Console. Finally it closes the connection
[Visual
Basic]
Public Sub
ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT OrderID, Customer
FROM Orders"
Dim myConnection As New SqlConnection(myConnString)
Dim myCommand As New SqlCommand(mySelectQuery,
myConnection)
myConnection.Open()
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine((myReader.GetInt32(0).ToString & ", "
& myReader.GetString(1)))
End While
Finally
' always call Close when done reading.
myReader.Close()
' always call Close when done reading.
myConnection.Close()
End Try
End Sub 'ReadMyData
[C#]
public void
ReadMyData(string myConnString)
{
string mySelectQuery = "SELECT OrderID, Customer FROM
Orders";
SqlConnection myConnection = new
SqlConnection(myConnString);
SqlCommand myCommand = new
SqlCommand(mySelectQuery,myConnection);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
Console.WriteLine(myReader.GetInt32(0) + ", " +
myReader.GetString(1));
}
}
finally
{
// always call Close when done reading.
myReader.Close();
// always call Close when done reading.
myConnection.Close();
}
}
[C++]
public:
void ReadMyData(String* myConnString)
{
String* mySelectQuery = "SELECT OrderID, Customer FROM
Orders";
SqlConnection* myConnection = new
SqlConnection(myConnString);
SqlCommand* myCommand = new
SqlCommand(mySelectQuery,myConnection);
myConnection->Open();
SqlDataReader* myReader = myCommand->ExecuteReader();
try
{
while (myReader->Read())
{
Console::WriteLine(S"{0}, {1}",
__box(myReader->GetInt32(0)),
myReader->GetString(1));
}
}
__finally
{
// always call Close when done reading.
myReader->Close();
// always call Close when done reading.
myConnection->Close();
}
}