ExecuteReader(CommandBehavior) Method
The following example creates a
SqlCommand, then executes it by passing a string that is SQL SELECT statement, and a string to use to connect to the data source. The
System.Data.CommandBehavior is then set to CloseConnection.
public void CreateSqlDataReader(string mySelectQuery,string myConnectionString)
{
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
myCommand.Connection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
}
Public Sub CreateSqlDataReader(mySelectQuery As String, _
myConnectionString As String)
Dim myConnection As New SqlConnection(myConnectionString)
Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
myCommand.Connection.Open()
Dim myReader As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
While myReader.Read()
Console.WriteLine(myReader.GetString(0))
End While
myReader.Close()
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