I got this error on server not in local and when facing this error, then i re-upload that related class file. after doing this problem solved but not permanently.
Error:
executenonquery requires an open and available connection. The
connection's current state is open.
Code:
int n;
try
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = DataConnection.Con;
cmd.CommandText = "sp_InsertUpdateDeleteValidationDate";
cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("#Task", "CheckExist");
cmd.Parameters.AddWithValue("#id", 0);
cmd.Parameters.AddWithValue("#AdId", "");
cmd.Parameters.AddWithValue("#Username", "");
cmd.Parameters.AddWithValue("#DOE", DOE);
cmd.Parameters.AddWithValue("#ExpieryDate", DateTime.Now);
cmd.Parameters.AddWithValue("#DOR", DateTime.Now);
cmd.Parameters.Add("#flag", SqlDbType.Int).Direction = ParameterDirection.Output;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
cmd.ExecuteNonQuery();
n = Convert.ToInt32(cmd.Parameters["#flag"].Value);
return n;
}
}
catch (SqlException Ex)
{
return 0;
}
You only create one connection in your DataConnection class. You should create a new connection for each database call and let the driver's connection pooling take care of efficiently reusing them.
change your DataConnection class to this:
public class DataConnection
{
public static SqlConnection Con
{
get
{
return new SqlConnection(ConfigurationManager
.ConnectionStrings["conn"].ConnectionString);
}
}
}
and use a using statement when you use the connection like in ekad's answer:
using (SqlConnection conn = DataConnection.Con)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
//use the command here
}
}
Looks like your SqlConnection is never closed. Try to use using statement to make sure that the SqlConnection is closed after executing cmd.ExecuteNonQuery()
int n;
try
{
using (SqlConnection conn = DataConnection.Con)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "sp_InsertUpdateDeleteValidationDate";
cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("#Task", "CheckExist");
cmd.Parameters.AddWithValue("#id", 0);
cmd.Parameters.AddWithValue("#AdId", "");
cmd.Parameters.AddWithValue("#Username", "");
cmd.Parameters.AddWithValue("#DOE", DOE);
cmd.Parameters.AddWithValue("#ExpieryDate", DateTime.Now);
cmd.Parameters.AddWithValue("#DOR", DateTime.Now);
cmd.Parameters.Add("#flag", SqlDbType.Int).Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteNonQuery();
n = Convert.ToInt32(cmd.Parameters["#flag"].Value);
return n;
}
}
}
catch (SqlException Ex)
{
return 0;
}
Related
New to C# and working on a Windows Form application. I am attempting to execute an update query against a SQL database, but keep running into "Must declare the scalar variable" error and I do not understand why.
The below code successfully opens the connection. My update statement is valid. Looking through a lot of posts on this topic and I am just not seeing my error... any help would be appreciated.
public void SetJobStatus(long JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
// use the connection here, and check to confirm it is open
if (conn.State != ConnectionState.Open)
{
if (conn != null)
{
conn.Close();
}
conn.Open();
}
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
command = new SqlCommand(strSql, conn);
//below AddWithValue gives error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#stationId".'
//command.Parameters.AddWithValue("#stationId", 1);
//command.Parameters.AddWithValue("#jobId", JobId);
//next I tried this, and the same error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#stationId".'
command.Parameters.Add("#stationId", SqlDbType.Int);
command.Parameters["#stationId"].Value = 1;
command.Parameters.Add("#jobId", SqlDbType.Int);
command.Parameters["#jobId"].Value = JobId;
adapter.UpdateCommand = new SqlCommand(strSql, conn);
adapter.UpdateCommand.ExecuteNonQuery();
}
}
I have checked your code and it's required some changes. Please try to run below code:
public void SetJobStatus(int JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
try
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
SqlCommand command = new SqlCommand(strSql, conn);
command.CommandType = CommandType.Text;
command.Parameters.Add("#stationId", SqlDbType.Int);
command.Parameters["#stationId"].Value = 1;
command.Parameters.Add("#jobId", SqlDbType.Int);
command.Parameters["#jobId"].Value = JobId;
command.ExecuteNonQuery();
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
Tips:
Always close connection after completion of task or in case of error.
Thanks to everyone who chimed in here. WSC's comment did the trick- changing adapter.UpdateCommand = command; worked. I tried three variations of adding parameters after making WSC's change- two of them worked, one did not.
My revised code is below. I have all three variations listed in the code- hopefully this will help somebody else out.
public void SetJobStatus(long JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
// use the connection here, and check to confirm it is open
if (conn.State != ConnectionState.Open)
{
if (conn != null)
{
conn.Close();
}
conn.Open();
}
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
command = new SqlCommand(strSql, conn);
//works
command.Parameters.AddWithValue("#stationId", GlobalVars.stationId);
command.Parameters.AddWithValue("#jobId", JobId);
//works
//command.Parameters.Add("#stationId", SqlDbType.Int);
//command.Parameters["#stationId"].Value = 5;
//command.Parameters.Add("#jobId", SqlDbType.Int);
//command.Parameters["#jobId"].Value = JobId;
//throws error at adapter.UpdateCommand.ExecuteNonQuery line:
//'The parameterized query '(#stationId int,#jobId int)update Jobmaster set jobstatus = 5 wh' expects the parameter '#stationId', which was not supplied.'
//command.Parameters.Add("#stationId", SqlDbType.Int, 5);
//command.Parameters.Add("#jobId", SqlDbType.Int, (int)JobId);
adapter.UpdateCommand = command;
adapter.UpdateCommand.ExecuteNonQuery();
}
}
Well, I work little bit with C # and I'm starting to work with Database with C # now, I've googled in several places and I am unable to identify where it is wrong, everywhere say I need to open a connection, but it is already open .
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
con.Open();
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Use using, takes care of the closing and disposal for you just in case you forget to do it explicitly. Put it inside the try, you have the connection open command outside the try so it wont catch any connection error. You probably want to look at parameterizing your command too.
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Table] (name, time) VALUES (#name,#time)", conn))
{
cmd.Parameters.AddWithValue("#name", "test");
cmd.Parameters.AddWithValue("#time", 1);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
you need to assign the command to the connection. eg:
private static void ReadOrderData(string connectionString)
{
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();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
I am trying to run a test query using sql. I know it is a simple concept, but i have tried everything I could find online and the following does not even run. It shows no errors but it does not run.
private static SqlConnection conn = new SqlConnection("<connection string>");
public static void connect()
{
conn.Open();
SqlCommand command = new SqlCommand("spTester 'this is tested'", conn);
command.ExecuteScalar();
conn.Close();
}
It seems that you want something like that:
private static void connect() {
// static SqlConnection conn is a bad idea, local variable is much better
// Do not forget to dispose IDisposable: using(...) {...}
using (SqlConnection conn = new SqlConnection("<connection string>")) {
// Do not forget to dispose IDisposable: using(...) {...}
using (SqlCommand command = new SqlCommand("spTester", conn)) {
// You're executing procedure, not ordinal SQL
command.CommandType = CommandType.StoredProcedure;
// It seems, that you should provide a parameter to your procedure:
//TODO: Change "#ParameterName" to actual one
command.Parameters.Add(new SqlParameter("#ParameterName", "this is tested"));
// You don't need any result value be returned
command.ExecuteNonQuery();
}
}
}
public static void connect()
{
conn.Open();
SqlCommand command = new SqlCommand("spTester 'this is tested'", conn);
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Close();
}
try doing this..
as u probably forgot to mention command.CommandType = CommandType.StoredProcedure; line
this is a simple example it will let you get started using SQLCOMMAND
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Try this :
public static void connect()
{
conn.Open();
SqlCommand command = new SqlCommand("spTester", conn);
command.CommandType = CommandType.StoredProcedure;
command.AddWithValue("#Parameter1","this is tested")
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Close();
}
I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
I created the below method which i tested and does return the correct data. Where I am confused is what is the proper way to populate individual textboxes on a form with the results from this method?
Rather than using an objectdatasource and then binding a gridview to the objectdatasource that works but I need more freedom to customize the form.
public MemberDetails GetMemberDetail(int membershipgen)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("usp_getmemberdetail", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#MEMBERSHIPGEN", SqlDbType.Int, 5));
cmd.Parameters["#MEMBERSHIPGEN"].Value = membershipgen;
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
reader.Read();
MemberDetails mem = new MemberDetails((int)reader["MEMBERSHIPGEN"], (string)reader["MEMBERSHIPID"], (string)reader["LASTNAME"],
(string)reader["FIRSTNAME"], (string)reader["SUFFIX"], (string)reader["MEMBERTYPESCODE"]);
reader.Close();
return mem;
}
catch (SqlException err)
{
throw new ApplicationException("Data error.");
}
finally
{
con.Close();
}
Something along the lines of:
var memberDetails = GetMemberDetail(12345);
textBox1.Text = memberDetails.Prop1;
textBox2.Text = memberDetails.Prop2;
...
Also I would refactor this method and make sure that I properly dispose disposable resources by wrapping them in using statements to avoid leaking unmanaged handles:
public MemberDetails GetMemberDetail(int membershipgen)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "usp_getmemberdetail";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#MEMBERSHIPGEN", membershipgen);
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (reader.Read())
{
return new MemberDetails(
reader.GetInt32(reader.GetOrdinal("MEMBERSHIPGEN")),
reader.GetString(reader.GetOrdinal("MEMBERSHIPID")),
reader.GetString(reader.GetOrdinal("LASTNAME")),
reader.GetString(reader.GetOrdinal("FIRSTNAME")),
reader.GetString(reader.GetOrdinal("SUFFIX")),
reader.GetString(reader.GetOrdinal("MEMBERTYPESCODE"))
);
}
return null;
}
}
}
Get the MemberDetails;
var memberDetails = GetMemberDetail(1);
Populate the textbox;
TextBox.Text = memberDetails.Property;
Jawaid outside of the correct answers that were provided below I would also set SqlConnection con = null; and
SqlCommand cmd = null; outside the try and inside the try put the following
con = new SqlConnection(connectionString);
this way if there is an Error when doing cmd.Parameters.Add -- you can trap that exception
also dispose of the reader object
if (reader != null)
{
((IDisposable)reader).Dispose();
// somthing like that .. do the same for con and cmd objects or wrap them in a using() {}
}
cmd = new SqlCommand("usp_getmemberdetail", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#MEMBERSHIPGEN", SqlDbType.Int, 5));
cmd.Parameters["#MEMBERSHIPGEN"].Value = membershipgen;