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.
Related
The first SQL is executing but the second one doesn't seem to work.
When i change the query to the first one it works just fine but when I put it like that it doesn't seem to work for some reason.
I've just started learning MySQL i'm really struggling with this one and understanding the language.
//Classic One that checks if the hwid is there
public void checkHWID(string HWID)
{
string line;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE HWID = #HWID", con))
{
cmd.Parameters.AddWithValue("#HWID", HWID);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
line = reader[1].ToString();
Console.Write(line);
con.Close();
}
else
{
updateHWID(HWID);
}
}
}
}
}
//This one doesn't seem to update the hwid but when i change the query to the first one it works just fine
public void updateHWID(String HWID)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO USERS(hwid) VALUES(#HWID)", connection))
{
command.Parameters.AddWithValue("#HWID", HWID);
connection.Close();
}
}
}
Your SQL statement in the updateHWID function isn't working primarily because it is missing the code that executes the command you created.
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO USERS(hwid) VALUES(#HWID)", connection))
{
command.Parameters.AddWithValue("#HWID", HWID);
command.ExecuteNonQuery(); // ADD THIS LINE
}
connection.Close();
Then assuming your table only requires the hwid and no other columns then this could work. If your table has other columns that don't allow nulls then you may get an error for the missing column values.
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.
I call ExecuteReader(); to get data, then i need to get another data with another query. My structure's been always like this :
class SomeClass
{
public static void Main(String[] args)
{
SqlConnection sqlConn = new SqlConnection();
sqlConn.ConnectionString = "some connection string"
SqlCommand SQLCmd = new SqlCommand();
SQLCmd.CommandText = "some query";
SQLCmd.Connection = sqlConn;
sqlConn.Open();
sqlReader = SQLCmd.ExecuteReader();
while (sqlReader.Read())
{
//some stuff here
}
sqlReader.Dispose();
sqlReader.Close();
sqlConn.Close();
SQLCmd.CommandText = "another query";
sqlConn.Open();
sqlReader = SQLCmd.ExecuteReader();
while (sqlReader.Read())
{
//some other stuff here
}
sqlReader.Dispose();
sqlReader.Close();
sqlConn.Close();
}
}
They share the same connection string. What else can they share ? Can they share same sqlConn.Open(); ? What is the proper way of resource allocating and avoiding errors ?
BTW it works as it is. Thanks in advance.
This is how I would write all of that:
class SomeClass
{
public static void Main(String[] args)
{
using (SqlConnection sqlConn = new SqlConnection("some connection string"))
{
sqlConn.Open();
using (SqlCommand comm = new SqlCommand("some query", conn))
using (var sqlReader = comm.ExecuteReader())
{
while (sqlReader.Read())
{
//some stuff here
}
}
using (SqlCommand comm = new SqlCommand("some query", conn))
using (var sqlReader = comm.ExecuteReader())
{
while (sqlReader.Read())
{
//some other stuff here
}
}
}
}
}
The using statement handles disposing of items when the block is finished. As for sharing stuff, you could leave the connection open across the commands.
The most important thing to dispose out of all of that would be the connection, but I tend towards honouring a using statement if an item is IDisposable regardless of what it actually does in the background (which is liable to change as it's an implementation detail).
Don't forget, there is also Multiple Active Result Sets (as demonstrated in this answer) from a single command and a single reader, where you advance the reader onto the next result set.
My slightly more flippant answer to how I might write all of that would be:
return connection.Query<T>(procedureName, param, commandType: CommandType.StoredProcedure);
Using Dapper ;-)
As alluded to in my comment - if possible, combine the two queries into one and then (if it still produces multiple result sets), use NextResult to move on.
Stealing Adam's structure, but with that change:
class SomeClass
{
public static void Main(String[] args)
{
using (SqlConnection sqlConn = new SqlConnection("some connection string"))
{
sqlConn.Open();
using (SqlCommand comm = new SqlCommand("some query; some other query;", conn))
using (var sqlReader = comm.ExecuteReader())
{
while (sqlReader.Read())
{
//some stuff here
}
if(sqlReader.NextResult())
{
while (sqlReader.Read())
{
//some other stuff here
}
}
}
}
}
}
The proper way is to wrap SqlConnections and SqlCommands in using-statements. This will force Dispose to be invoked on the objects when the using block is left, even if an Exception is thrown. (This is not the case with your current code.)
Something in the line of
using(var cnn = new SqlConnection("connectionstring")){
cnn.Open();
using(var cmd = new SqlCommand("SELECT 1")){
var reader = cmd.ExecuteReader();
while(reader.Read()) { /* doStuff */ }
}
}
Regardless of the approach Close/Dispose will not actually close the connection since connection setup is very expensive. It will just return the connection to a connection pool and allow other commands/readers to use it.
To manage resource you can use using like as shown under
...
SQLCmd.CommandText = "some query";
SQLCmd.Connection = sqlConn;
sqlConn.Open();
//using will dispose reader automatically.
using(sqlReader = SQLCmd.ExecuteReader())
{
while (sqlReader.Read())
{
//some stuff here
}
}
//sqlReader.Dispose();
//sqlReader.Close();
//sqlConn.Close();
SQLCmd.CommandText = "another query";
//no need to open connection again.
// sqlConn.Open();
// sqlReader = SQLCmd.ExecuteReader();
using(sqlReader = SQLCmd.ExecuteReader())
{
while (sqlReader.Read())
{
//some stuff here
}
}
//sqlReader.Dispose();
//sqlReader.Close();
//sqlConn.Close();
you can use using only for those classes which have implemented IDispose interface.
in your example you can use SqlConnection and SqlCommand also with using code block.
Use 'using', you don't need to manually close and dispose.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("spTest", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#employeeid", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}
Open a new connection every time you need it is a best practices. ADO.net use connection pool to menage connection.
http://msdn.microsoft.com/it-it/library/8xx3tyca(v=vs.110).aspx
Dont forget your try catch statements though :)
class SomeClass
{
public static void Main(String[] args)
{
using (SqlConnection sqlConn = new SqlConnection("some connection string"))
{
try{
sqlConn.Open();
using (SqlCommand comm = new SqlCommand("some query", conn))
using (var sqlReader = comm.ExecuteReader())
{
while (sqlReader.Read())
{
//some stuff here
}
}
using (SqlCommand comm = new SqlCommand("some query", conn))
using (var sqlReader = comm.ExecuteReader())
{
while (sqlReader.Read())
{
//some other stuff here
}
}
}
catch()
{
// Do exception catching here or rollbacktransaction if your using begin transact
}
finally
{
sqlConn.Close();
}
}
}
}
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.
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.