Answer the question
In order to leave comments, you need to log in
Why is SQL Server not responding?
Hello. There is a small piece of code for updating a field in a table
private void SetResponsibleInSQL(long id, long resp)
{
using (SqlConnection con = new SqlConnection(@"Data Source=SERVER;Initial Catalog=DB;User ID=su;Password=123123;Timeout=300;"))
{
con.Open();
using (SqlCommand comm = new SqlCommand()) {
comm.Connection = con;
comm.CommandTimeout = 300;
comm.CommandText = String.Format("update Contractor set Responsible = {0} where Id = {1}", resp, id);
comm.ExecuteNonQuery();
comm.Dispose();
comm.Cancel();
}
con.Close();
}
}
_con.Open();
SetResponsibleInSQL();
_con.Close();
//---------------------------
private void SetResponsibleInSQL()
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = _con;
comm.CommandTimeout = 30;
comm.CommandText = "BEGIN TRANSACTION;\n" + sqlQuery + "\nCOMMIT TRANSACTION;";
Console.WriteLine(comm.CommandText);
comm.ExecuteNonQuery();
}
}
Answer the question
In order to leave comments, you need to log in
For cyclic execution of such code, they are punished with a workplace in the basement without a window. Dear - try to make 1 script, not hundreds. Win the darkness of time and the server will breathe a sigh of relief. Yes, the script will be more difficult and trickier, but optimizing interaction with the database is not an easy task at all, and here you create hundreds of connections / disconnections with one client, who knows what.
UPD: I read a little into the code and did not understand some of your movements.
1) why do using (SqlConnection con = new SqlConnection() and then con.Open(); and con.Close() on exit? well suppose the connection is not opened when object is created, but when leaving using and AUTOMATICALLY calling con .Dispose() will close the connection
2)
using (SqlCommand comm = new SqlCommand()) {
comm.Dispose();
comm.Cancel();
}
Firstly, Dispose is called when you go beyond the boundaries of using, and why you call Cancel I have no idea at all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question