C# Code Snippet - Get Data From SqlDataReader using open connection
(C-Sharp) C# code snippet connects to SQL server and executes SQL statement and return SqlDataReader. GetSqlDataReader returns SqlDataReader using open database connection and SQL statement.
Bookmark:
C# Code Snippet - Get Data From SqlDataReader using open connection
This .Net C# code snippet connect connects to SQL server and executes SQL statement and return SqlDataReader. To use this function simply provide open database connection and SQL statement. This function uses SqlClient name space to get data using SqlDataReader. Modify the exception handling section for your project requirements.
01 | public System.Data.SqlClient.SqlDataReader GetSqlDataReader( |
02 | ref System.Data.SqlClient.SqlConnection _SqlConnection, |
06 | System.Data.SqlClient.SqlDataReader _SqlDataReader = null ; |
12 | System.Data.SqlClient.SqlCommand _SqlCommand = |
13 | new System.Data.SqlClient.SqlCommand(_SQL, _SqlConnection); |
16 | _SqlDataReader = _SqlCommand.ExecuteReader(); |
18 | catch (Exception _Exception) |
22 | Console.WriteLine(_Exception.Message); |
29 | return _SqlDataReader; |
Here is a simple example showing how to use above function (GetSqlDataReader) to connect to SQL database and get SqlDataReader for given SQL statement.
02 | System.Data.SqlClient.SqlConnection _SqlConnection = new System.Data.SqlClient.SqlConnection(); |
05 | _SqlConnection.ConnectionString = "Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERID;Pwd=PASSWORD;" ; |
10 | _SqlConnection.Open(); |
12 | catch (Exception _Exception) |
15 | Console.WriteLine(_Exception.Message); |
20 | if (_SqlConnection != null && _SqlConnection.State == ConnectionState.Open) |
24 | System.Data.SqlClient.SqlDataReader _SqlDataReader = GetSqlDataReader( |
28 | "SELECT NAME, PRICE, COST FROM INVENTORY" ); |
31 | if (_SqlDataReader != null && _SqlDataReader.HasRows) |
33 | Console.WriteLine(_SqlDataReader[ "NAME" ].ToString()); |
37 | if (_SqlDataReader != null ) |
39 | _SqlDataReader.Close(); |
40 | _SqlDataReader.Dispose(); |
44 | _SqlConnection.Close(); |
C# Keywords Used:
- SqlDataReader
- SqlConnection
- ConnectionString
- SqlCommand
- ExecuteReader
- Exception
Code Snippet Information:
- Applies To: .Net, C#, CLI, SQL, SQL Server, SQL Client, Connection String, Database Connection, SQL Data Reader
- Programming Language : C# (C-Sharp)
External Resources: