Reads a forward-only stream of rows from SQL Server.
The following example creates a
SqlConnection, a
SqlCommand, and a
SqlDataReader. The example reads through the data, writing it out to the console. Finally, the example closes the
SqlDataReader, then the
SqlConnection.
|
|---|
public void ReadMyData(string myConnString) {
SqlConnection sqlConnection = new SqlConnection(myConnString);
SqlCommand sqlCommand = (SqlCommand)sqlConnection.CreateCommand();
sqlCommand.CommandText = "SELECT DeptNo, DName, Loc FROM Test.Dept";
sqlConnection.Open();
SqlDataReader sqlReader = sqlCommand.ExecuteReader();
try {
// Always call Read before accessing data.
while (sqlReader.Read()) {
Console.WriteLine(sqlReader.GetInt32(0).ToString() + " " +
sqlReader.GetString(1) + " " + sqlReader.GetString(2));
}
}
finally {
// always call Close when done reading.
sqlReader.Close();
// Close the connection when done with it.
sqlConnection.Close();
}
} |
|
|---|
Public Sub ReadMyData(ByVal myConnString As String)
Dim sqlConnection As New SqlConnection(myConnString)
Dim sqlCommand As SqlCommand = sqlConnection.CreateCommand()
sqlCommand.CommandText = "SELECT DeptNo, DName, Loc FROM Test.Dept"
sqlConnection.Open()
Dim sqlReader As SqlDataReader = sqlCommand.ExecuteReader()
Try
' Always call Read before accessing data.
While sqlReader.Read()
Console.WriteLine(String.Concat(sqlReader.GetInt32(0).ToString(), " ", _
sqlReader.GetString(1), " ", sqlReader.GetString(2)))
End While
Finally
' always call Close when done reading.
sqlReader.Close()
' Close the connection when done with it.
sqlConnection.Close()
End Try
End Sub |