Can I close a SqlDataReader after DataBind() - c#

Say I do something like this
using (SqlDataReader allUsersDataSource = AdminDB.GetUsers())
{
// bind all portal users to dropdownlist
allUsers.DataSource = allUsersDataSource;
allUsers.DataBind();
}
Will the dataBinded still behave correctly or does it need the SqlDataReader to be undisposed?
EDIT: Additional Information
public static SqlDataReader GetUsers()
{
// Create Instance of Connection and Command Object
using (SqlConnection myConnection = new SqlConnection( (string) PortalSettings.GetPortalSetting("ConnectionString")))
using (SqlCommand myCommand = new SqlCommand("dbo.GetUsers", myConnection))
{
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Open the database connection and execute the command
myConnection.Open();
SqlDataReader dr = myCommand.ExecuteReader();
// Return the datareader
return dr;
}
}

The code you are using to bind the data uses using block
using (SqlDataReader allUsersDataSource = AdminDB.GetUsers())
{
// bind all portal users to dropdownlist
allUsers.DataSource = allUsersDataSource;
allUsers.DataBind();
}
using takes only IDisposable objects and calls the Dispose method when the block execution ends. So you need not to worry about Disposing the Reader object here.

Related

Ado.Net: Does closing SqlCommand cause closing DataReader

Today I looked through some legacy code and I have began worrying. It is required to close a DataReader explicitly.
My question is: does closing the SqlCommand close the associated DataReader as well?
This is my code:
using (var conn = new SqlConnection(this.ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "House_GetHouseById";
SqlCommandBuilder.DeriveParameters(cmd);
cmd.Parameters["#HouseId"].Value = houseId;
var reader = cmd.ExecuteReader())
while (reader.Read())
{
}
}
}
In this snippet from msdn command is not closed explicitly:
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
No. SqlCommand.Dispose is essentially a no-op¹, and it won't close your SqlDataReader.
Technically, closing the SqlConnection should close all resources, see this question for details:
Is closing/disposing an SqlDataReader needed if you are already closing the SqlConnection?
However, this is bad practice -- you are relying on an implementation detail of the SqlClient library. The "correct" way would be to dispose (via Dispose or using) everything that is IDisposable. Thus, your code should be written as follows:
using (var conn = new SqlConnection(this.ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "House_GetHouseById";
SqlCommandBuilder.DeriveParameters(cmd);
cmd.Parameters["#HouseId"].Value = houseId;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// do something
}
}
}
}
¹ Note that this is not true for the command classes of other libraries such as OleDbCommand and SqlCeCommand, so don't get in the habit of not disposing commands.
You could always wrap the datareader in a using directive so that the command is closed as soon the execution is out of the scope,just like the sqlcommand
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
} // reader is closed here
reader.Close(); //is another way but its too easy to be forgotten.

How to get data from database and put it into a variable in c#?

I'm working on "Time Table Scedualing using genetic algorithm project"
using C# and Sql server..
I divided the Project to 3 Layers (Data Access Layer , business Layer , And interfaces)
Data access layer contains:
(constructor initialize the connection object, Method to open the connection,Method to open the connection ,Method to read data from database, Method to insert , update ,delete data from database)
for example:
//Method to insert , update ,delete data from database
public void ExecuteCommand(string stored_procedure, SqlParameter[] param)
{
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = stored_procedure;
sqlcmd.Connection = sqlconnection;
if (param != null)
{
sqlcmd.Parameters.AddRange(param);
}
sqlcmd.ExecuteNonQuery();
}
Business Layer Contains class for each form
for example: ADD_PROF.class for "Add Professor Form"
....................
Now to get all data about professors from database,I create (GET_ALL_PROF) procedure and write this code into ADD_PROF Class
public DataTable GET_ALL_PROF() //copied and pasted down for verfing
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DataTable Dt = new DataTable();
Dt = DAL.SelectData("GET_ALL_PROF", null);
DAL.Close();
return Dt;
}
My Problem is ... I don't know how to get (Professors ID) from professor table in database and put it into a variable to pass it in genetic algorithm code IN C#?
the procedure in sql is
Create proc [dbo].[get_id_PROF]
as
select ID_PROF from [dbo].[PROFESSOR]
You could use a SqlDataReader for reading the data from your database and simply use it to store data from your database in your variables.
int professorId;
private static void ReadOrderData(string connectionString)
{
string queryString = "select ID_ST from [dbo].[PROFESSOR];";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// Call Read before accessing data.
if (reader.HasRows())
{
reader.Read();
professorId = reader.GetInt32(0);
// Call Close when done reading.
reader.Close();
}
}
}
}
Or you could try this to use a Stored Procedure:
int professorId;
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Data is accessible through the DataReader object here.
reader.Read();
professorId = reader.GetInt32(0);
}
}
SqlDataReader
Helper Link
Helper Link

Oracle DataReader Closing Connection before I can read data

I have a function that returns an OracleDataReader object. Here it is :
public OracleDataReader executeCommand(string query)
{
using (conn)
{
conn.ConnectionString = connectionString;
conn.Open();
OracleCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
OracleDataReader reader = cmd.ExecuteReader();
return reader;
}
}
When I tried to to get data with reader in another class i get an exception:
public Person GetPersonById(int id)
{
OracleDBOp db = new OracleDBOp();
String query = "select * from test_person where id=" + id;
OracleDataReader reader = db.executeCommand(query);
Person person = null;
person = new Person(Convert.ToInt32(reader["id"]),reader["first_name"].ToString(),reader["last_name"].ToString());
return person;
}
Exception
Invalid attempt to GetOrdinal when reader is closed.
What is the problem? I am not closing the reader?
Your code closes the connection as soon as the using scope is exited, so any attempts to read will fail:
using (conn)
{
conn.ConnectionString = connectionString;
conn.Open();
...
return reader;
} --> Disposes of connection, which closes it, so reader can't read.
One option is to instead of placing the connection in the using block, if you intend passing the reader outside the control of the method which owns the connection, you can specify CommandBehavior.CloseConnection to close the connection when the reader is closed, but do NOT close or dispose of the connection i.e.
OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
IMO, a safer pattern (provided that you play nicely with the iterator, e.g. with foreach), without leaving the responsibility of the disposal of resources to the caller, and without passing the reader outside of a function, would be to use yield return, although this will change the way your code works:
public IEnumerable<Person> RetrievePeople()
{
using (var conn = new OracleConnection(connString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = query;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new new Person(
Convert.ToInt32(reader["id"]),
reader["first_name"].ToString(),
reader["last_name"].ToString());
}
}
}
}
}
This way you don't need to pass the reader around, yet, the connection will be remain open until the iterator completes. This has the benefit of retaining the lazy evaluation approach of the reader, without actually passing the reader around, and without the issue of who is going to clean up the connections afterwards.

Issue with calling two methods in data access method

I have this method:
public bool ActivateUser(string username, string key)
{
var user = this.GetUser(username, true);
if (user != null)
{
if (user.NewEmailKey == key)
{
string query = "usp_ActivateUser";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#p_Username", username);
cmd.Parameters.AddWithValue("#p_LastModifiedDate", DateTime.Now);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
cmd.ExecuteNonQuery();
return true;
}
}
}
}
else
return false;
}
else
return false;
}
As you can see I call GetUser() method first to get user and later use data for another database call. But something goes wrong.
There is already an open DataReader associated with this Command which must be closed first.
Here is the get user method:
public User GetUser(string username, bool nonMembershipUser)
{
string query = "usp_GetUser";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#p_Username", username);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{...
Your problem is here.
using (SqlDataReader reader = cmd.ExecuteReader())
{
cmd.ExecuteNonQuery();
return true;
}
You are calling cmd.ExecuteNonQuery() but the command is already being used by the reader inside this using block.
Since your code doesn't really do anything meaningful with the reader why not remove the block entirely and call cmd.ExecuteNonQuery() ?
Why do you do cmd.ExecuteReader() in the using statement, then cmd.ExecuteNonQuery(); on the very next line?
Why use the ExecuteReader() at all as you are simply returning from the database call without checking the result - ExecuteNonQuery will suffice for this.
this is the problem, in ActivateUser:
using (SqlDataReader reader = cmd.ExecuteReader())
{
cmd.ExecuteNonQuery();
return true;
}
You can't open a Reader on an SqlCommand object and then execute another query on that command objct without first closing the Reader - which won't happen until that last "}".
Actually I'm not sure you even need the Reader in this case - did you maybe copy/paste from your GetUser function? All you should need is
cmd.ExecuteNonQuery();
return true;
Also, I would consider wrapping code to execute readers,queries, etc, into some functions so you can re-use them. Here's what I normally use as a wrapper for readers:
public static DataTable ExecuteReader (string query,CommandType commType, params SqlParameter[] Paramerters)
{
try
{
using (SqlConnection conn = new SqlConnection("your connection string here")
{
conn.Open();
using (SqlCommand comm = new SqlCommand(conn,query))
{
conn.CommandType=commType;
if (Parameters!=null) comm.Parameters.AddRange(Parameters);
DataTable dt = new DataTable();
using (SqlDataReader reader = comm.ExecuteReader())
{
dt.Load(reader);
}
return dt;
}//end using command
}//end using connection
}
catch(Exception)
{
throw;
}
}//end function
and you can write simple wrappers for nonquery, nonreader, etc, as well.

Multiple SQL queries asp.net c#

I need to run several queries inside one function, will I have to create a new SqlConnection for each? Or having one connection but different SqlCommands works too?
Thanks,
EDIT: Will this work?
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(query3, conn))
{
cmd.ExecuteNonQuery();
}
}
Using the MDSN Documentation as a base:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql1 = "SELECT ID,FirstName,LastName FROM VP_PERSON";
string sql2 = "SELECT Address,City,State,Code FROM VP_ADDRESS";
using (SqlCommand command = new SqlCommand(sql1,connection))
{
//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
using (SqlCommand command = new SqlCommand(sql2,connection))
{
//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
// If you don't using using on your SqlCommands you need to dispose of them
// by calling command.Dispose(); on the command after you're done.
} // the SqlConnection will be disposed
It doesn't matter which way you go.
SqlConnections are pooled by the operating system. You could literally open and close a connection thousands of times in a row and not incur any performance or other penalty.
How it works is:
Application makes a request to create a db connection (var c = new SqlConnection(...))
The Operating Systems connection pool looks to see if it has a connection sitting idle. If it does, you get a reference to that. If not then it spins up a new one.
Application indicates it is finished with the connection (c.Dispose())
Operating System keeps the connection open for a certain amount of time in case your app, or another one, tries to create another connection to that same resource.
If that connection stays idle until a timeout period passes then the OS finally closes and releases.
This is why the first time you make a connection to a database it might take a second to start before the command(s) can be processed. However if you close it and reopen it then the connection is available immediately. More information is here: http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx
Now, as to your code, generally speaking you open 1 SqlConnection each time you make a SqlCommand call; however, it is perfectly acceptable/reasonable to make multiple SqlCommand calls while within the same block under the SqlConnection using clause.
Just bear in mind that you do NOT want to keep a SqlConnection object hanging around in your code for any longer than is absolutely necessary. This can lead to a lot of potential issues, especially if you are doing web development. Which means it's far better for your code to open and close 100 SqlConnection objects in rapid succession than it is to hold onto that object and pass it around through various methods.
Having one SqlConnection and many SqlCommands will work fine, however you must make sure that you dispose of any SqlDataReaders that are returned from previous commands before attempting to run additional commands.
using (SqlConnection conn = new SqlConnection())
{
conn.Open()
using (SqlCommand cmd = new SqlCommand("SELECT myrow FROM mytable", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Handle first resultset here
}
}
using (SqlCommand cmd = new SqlCommand("SELECT otherrow FROM othertable", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Handle second resultset here
}
}
}
Alternaitvely you might be able to combine your commands up into one batch and instead process multiple resultsets, like this:
using (SqlConnection conn = new SqlConnection())
{
conn.Open()
using (SqlCommand cmd = new SqlCommand("SELECT myrow FROM mytable; SELECT otherrow FROM othertable", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Handle first resultset here, and then when done call
if (reader.NextResult())
{
// Handle second resultset here
}
}
}
}
When you are processing many resultsets you will find that batching together queries like this can significantly improve performance, however it comes at the price of added complexity in your calling code.
Open only one SQLConnection
Use the keyworkd Using as it will automatically dispose the connection.
If you open connection for each one , it can have performance problems.
Example:
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code shows how you can use an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}
One more example:
public DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("your connection here")
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "your stored procedure here";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return dt;
}
Purely as an alternative to the using statements:
SqlConnection con = new SqlConnection(myConnectionString);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = #"SELECT [stuff] FROM [tableOfStuff]";
con.Open();
SqlDataReader dr = null;
try
{
dr = cmd.ExecuteReader();
while(dr.Read())
{
// Populate your business objects/data tables/whatever
}
}
catch(SomeTypeOfException ex){ /* handle exception */ }
// Manually call Dispose()...
if(con != null) con.Dispose();
if(cmd != null) cmd.Dispose();
if(dr != null) dr.Dispose();
The major difference between this and the using statements, is this will allow you to handle exceptions more cleanly.

Categories

Resources