Joel.Net.DatabaseUtility.dll Class Library

DatabaseUtility.ExecuteReader Method (String, String, CommandType, SqlParameter[])

Sends the System.Data.SqlClient.SqlCommand.CommandText to the System.Data.SqlClient.SqlCommand.Connection, and builds a System.Data.SqlClient.SqlDataReader.

[Visual Basic]
Shared  OverloadsPublic Function ExecuteReader( _ 
   ByVal database As String, _ 
   ByVal commandText As String, _ 
   ByVal commandType As CommandType, _ 
   ByVal ParamArray parameters As SqlParameter() _ 
) As SqlDataReader
[C#]
public static SqlDataReader ExecuteReader(
   string database,
   string commandText,
   CommandType commandType,
   params SqlParameter[] parameters
);
[C++]
public: static SqlDataReader* ExecuteReader(
   String* database,
   String* commandText,
   CommandType commandType,
   SqlParameter* parameters __gc[]
);
[JScript]
public static function ExecuteReader(
   String database,
   String commandText,
   CommandType commandType,
   SqlParameter[] parameters
): SqlDataReader;

Parameters

database
Changes the current database for an open System.Data.SqlClient.SqlConnection.
commandText
The text of the query.
commandType
Specifies how a command string is interpreted.
parameters
A list of type System.Data.SqlClient.SqlParameter that maps to the System.Data.SqlClient.SqlCommand.

Return Value

A System.Data.SqlClient.SqlDataReader object.

Example

[C#, Visual Basic] The following example creates a SqlCommand, then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. CommandBehavior is set to CloseConnection.

[C#]
DatabaseUtility.Connection = new SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;");

SqlDataReader reader = DatabaseUtility.ExecuteReader(
    "Northwind",
    "SELECT * FROM Customers WHERE CustomerID = @CustomerID",
    CommandType.Text,
    new SqlParameter("@CustomerID", "ALFKI")
);

while (reader.Read()) {
    Console.WriteLine("ExecuteReader: {0}, {1}, {2}", reader["CustomerID"], reader["CompanyName"], reader["ContactName"]);
}

reader.Close(); // this will close the connection (only if connection was not opened before ExecuteReader)
[Visual Basic]
DatabaseUtility.Connection = New SqlConnection("Server=127.0.0.1;Database=Northwind;Uid=sa;Pwd=;")

SqlDataReader reader = DatabaseUtility.ExecuteReader( _
    "Northwind", _
    "SELECT * FROM Customers WHERE CustomerID = @CustomerID", _
    CommandType.Text, _
    new SqlParameter("@CustomerID", "ALFKI") _
)

While (reader.Read()) 
    Console.WriteLine("ExecuteReader: {0}, {1}, {2}", reader["CustomerID"], reader["CompanyName"], reader["ContactName"])
End While

reader.Close() // this will close the connection (only if connection was not opened before ExecuteReader)

See Also

DatabaseUtility Class | Joel.Net Namespace | DatabaseUtility.ExecuteReader Overload List