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();
}
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();
}
}
Okey, so I am new to C# and I have tried to move my Mysql connection string to another class but I can't seem to open the connection once I call the method and I really can't see what's wrong.
So this is the connection method in a new class(DatabaseC)
public static void Connection()
{
try
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["cs"];
string conn = conSettings.ConnectionString;
MySqlConnection connect = new MySqlConnection(conn);
connect.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
And here I call the method in a Form
private bool validate_login(string u, string p)
{
DatabaseC.Connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM account WHERE Password COLLATE latin1_general_cs = #password AND User COLLATE latin1_general_cs = #username";
cmd.Parameters.AddWithValue("#username", u);
cmd.Parameters.AddWithValue("#password", p);
MySqlDataReader login = cmd.ExecuteReader();
}
Sorry for if the code looks bad but as I said im new.
You should return the instance of the MySqlConnection opened
public static MySqlConnection Connection()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["cs"];
string conn = conSettings.ConnectionString;
MySqlConnection connect = new MySqlConnection(conn);
connect.Open();
return connect;
}
Now you can change your calling code to receive the connection and use it
private bool validate_login(string u, string p)
{
using(MySqlConnection cnn = DatabaseC.Connection())
using(MySqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = "......"
...
using(MySqlDataReader reader = cmd.ExecuteReader())
{
.....
} // Here the reader is closed and destroyed
} // Here the connection closed and destroyed with the command
}
Notice that a connection is a disposable object and thus you should be sure to destroy it once you have finished to use it. This is the work of the using statement.
Another problem fixed with this code is the fact that a command needs to know the connection to use, your actual code doesn't link the command with the connection and thus it cannot work.
EDIT: you comment below should be added to the answer. The Try/Catch in the Connection method should be removed. You do nothing there and catching the exception creates only complications in the calling code that need to handle a null return value. It is better to let the exception bubble up until there is a method that has something to do with that (like logging it for example)
Actually you need to open the connection where you are using the connection, try this way
public static MySqlConnection Connection()
{
try
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["cs"];
string conn = conSettings.ConnectionString;
MySqlConnection connect = new MySqlConnection(conn);
return connect;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
then
private bool validate_login(string u, string p)
{
DatabaseC.Connection().Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM account WHERE Password COLLATE latin1_general_cs = #password AND User COLLATE latin1_general_cs = #username";
cmd.Parameters.AddWithValue("#username", u);
cmd.Parameters.AddWithValue("#password", p);
MySqlDataReader login = cmd.ExecuteReader();
I'm a beginner programmer with C#. I'm trying to develop an application that it connects to a database and do the typical operations like insert, delete, update and get.
I'm getting a error with the database connection. I'm working with SQL Server 2012, where I have create a database called company.
This is my code:
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
What is the error? I get an exception on this line:
command.Connection.Open();
Thanks in advance
SqlConnection con = new SqlConnection("Your Connection String Goes here");
You should assign connection to SqlCommand object like this
SqlCommand command = new SqlCommand();
command.Connection = con;
or
SqlCommand command = new SqlCommand("YourQuery",con);
Some Important Steps to Execute Command
1: Create SqlConnection Object and Assign a connection string to that object
SqlConnection con = new SqlConnection("Your Connection String Goes here");
or
SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
2: Create SqlCommand Object and assing a command Text(Your Query) and connection string to that object
SqlCommand command = new SqlCommand("Select * from Products",con);
or
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";
You can also specify CommandType
command.CommandType =CommandType.Text;
/* if you are executing storedprocedure CommandType Will be
=> CommandType.StoredProcedure; */
then You can Execute Command Like this
try
{
con.Open();
int TotalRowsAffected = command.ExecuteNonQuery();
}
catch(Exeception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.Close();
}
Just an FYI: An alternative to the try finally blocks, which ensure the database connection gets closed is to use the using statement such as:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
try
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (InvalidOperationException)
{
//log and/or rethrow or ignore
}
catch (SqlException)
{
//log and/or rethrow or ignore
}
catch (ArgumentException)
{
//log and/or rethrow or ignore
}
}
Refer to the MSDN documentation for the SqlCommand class here, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx, and look up the ExecuteNonQuery() method, which is used to execute INSERT, UPDATE, and DELETE statements. Then look up ExecuteScalar() method that you can use to execute SELECT statements that return a single value. You can use ExecuteReader() to return a SqlDataReader for SELECT statements that return multiple columns.
not initialize sqlcommand connections, way for initialize this is :
command.Connection=con;
this is complete code for you :
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection=con;
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
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 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;
}