Represents a SQL statement or stored procedure to execute against SQL Server.
The following example uses the
ExecuteReader method of
SqlCommand, along with
SqlDataReader and
SqlConnection, to select rows from a table.
public void ReadMyData(string myConnString)
{
string mySelectQuery = "SELECT DeptNo, DName FROM Test.Dept";
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).ToString() + ", " + myReader.GetString(1));
}
}
finally
{
// always call Close when done reading.
myReader.Close();
// always call Close when done reading.
myConnection.Close();
}
}
Public Sub ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT DeptNo, DName FROM Test.Dept"
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 with connection.
myConnection.Close()
End Try
End Sub
Target Platforms: Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2