I m running a piece of code for scheduler in my project. But it is not working as expected.
private void Initiate_User(string strEmpCard)
{
//conn.Open();
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString() + "", conn);
ObjPriCmd.ExecuteNonQuery();
}
The debugger stops and opens a form after my ExecuteNonQuery() line is debugged. I am not able to trace the error also. what is wrong here ??
UPDATE
My error query
insert into p_emp_clearance_hdr
(Emp_mkey,
Emp_card_no,
RA_1,
RA_2,
Depatment,
Sub_Department,
Date_of_Joining,
Resignation_date,
Last_Working_Days,
UserId)
select
em.mkey,
em.emp_card_no,
em.Reporting_To,
em.Reporting_To2,
em.Department_mkey,
em.SubDept_mkey,
convert(varchar(10), em.resig_date, 103) resig_date,
convert( varchar(10), em.Dt_Of_Join, 103) Dt_Of_Join,
convert(varchar(10), em.Dt_of_leave, 103) Dt_of_leave,
um.mkey
from emp_mst em join user_mst um
on em.mkey = um.Employee_mkey
where em.mkey = #emp_mkey
As you explained in comments, you are getting error:
ExecuteNonQuery: Connection property has not been initialized.
It means you have not initialized the connection. You have just declared it:
SqlConnection conn;
You should do like:
conn = new SqlConnection(#"you connection string");
//then your code
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString(), conn);
ObjPriCmd.ExecuteNonQuery();
The best practice:
You should use a SqlCommand property CommandType to define that you're calling a StoredProcedure when calling from C#. And define parameters using SqlCommand .Parameters.Add it handles the SqlInjection issues itself.
conn = new SqlConnection(#"you connection string");
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// parameter name , parameter type parameter value
cmd.Parameters.Add("#parameter name", SqlDbType.VarChar).Value = strEmpCard.ToString();
con.Open();
cmd.ExecuteNonQuery();
}
You can Try it with USing Statement:-
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Parameter Name", Type).Value = "Value of Parameter";
conn.Open();
cmd.ExecuteNonQuery();
}
Related
How come I'm getting this error while trying to update my database?
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed
Here is the code:
cmd1 = new SqlCommand("UPDATE [guitarBrands] SET type = #type, name = #name, image = #image WHERE id = #id", con1);
con1.Open();
cmd1.Parameters.Add(new SqlParameter("type", newType.Text));
cmd1.Parameters.Add(new SqlParameter("name", newName.Text));
cmd1.Parameters.Add(new SqlParameter("image", newImage.Text));
cmd1.Parameters.Add(new SqlParameter("id", id));
cmd1.ExecuteNonQuery();
con1.Close();
cmd1.Parameters.Clear();
cmd = new SqlCommand("UPDATE [guitarItems] SET brand = #brand WHERE id = #id", con1);
con.Open();
cmd.Parameters.Add(new SqlParameter("brand", newName.Text));
cmd.Parameters.Add(new SqlParameter("id", id));
cmd.ExecuteNonQuery();
con.Close();
cmd.Parameters.Clear();
To avoid these sort of issues, it is recommended you utilize the tower of power.
using(var connection = new SqlConnection(dbConnection))
{
connection.Open();
using(var command = new SqlCommand(query, connection)
{
}
using(var command = new SqlCommand(query, connection)
{
}
}
So the beauty of the tower of power, the using block will implement via within the given code block. So this will make it clear, that both these commands are utilizing the same connection from the using. Also, once the code is out of scope it will implement the IDispose, which will call the garbage collector to free up your resources.
Also, should you choose. The SqlCommand, accepts a parameter array. So if you utilize a method call, you could simply do:
public static GetExample(string query, params SqlParameter[] parameters)
{
using(var connection = new SqlConnection("YourDbConnection"))
using(var command = new SqlCommand("YourQuery", connection))
{
connection.Open();
if(parameters != null)
if(parameters.Any())
command.Parameters.Add(parameters);
command.ExecuteNonQuery();
}
}
I can't recall if the collection is a add, add range, or concat. But either way the option exist.
cmd = new SqlCommand("UPDATE [guitarItems] SET brand = #brand WHERE id = #id", con1);
replace this line to this
cmd = new SqlCommand("UPDATE [guitarItems] SET brand = #brand WHERE id = #id", con);
In your code you use Connexion "con1" in both Commands "cmd1" and "cmd". It is OK to use just one connexion for both commands but then you should leave the connexion open until both command are executed.
In your case you choose to use a new connexion "con" for the second command but you reopen "con1".
So you get an error because "con" is never opened.
In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
I have this code, and when I execute it, it doesn't work
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = 'username', pass = '#password' where IDetudient='#ID ' ", con);
con.Open();
cmd.Parameters.AddWithValue("#username", text_name.Text);
cmd.Parameters.AddWithValue("#password",Convert.ToDecimal( textBox1.Text));
cmd.Parameters.AddWithValue("#ID", Convert.ToInt64( text_id.Text));
cmd.ExecuteNonQuery();
con.Close();
Try this way:
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient=#ID", con);
I had the same issue. The thing is, in the query you just pass the name of the parameter.
Your sql command't test would be:
var cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient = #ID ", con);
Also, you will need to validate if conversion from string to int64 if fails or not.
In my code neither of these queries appear to be running. The debug label is printing as "end" so it is executing something inside that code block, just appears it doesn't like the queries?
// Check input is all valid
if (Page.IsValid)
{
debug.Text = "begin";
using (SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand(
"UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO tblSiteSettings (allowProductRatings, allowComments, " +
"siteName, settingDate, isActive) VALUES (#allowRatings, " +
"#allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cn.Close();
}
debug.Text = "end";
}
}
A few questions:
Why are they not executing?
In classic ASP for inserts, updates and deletes I would use con.Execute(query) as supposed to using a recordset, am I running my update statement correctly here?
Is my design of the queries good, or should I be executing them in a different manner?
The reason it's not doing anything is because you're not actually executing the queries. What you need to do is:
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblSiteSettings (allowProductRatings, allowComments, siteName, settingDate, isActive) VALUES (#allowRatings, #allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
It's the line cmd.ExecuteNoneQuery(); that you're missing. There are various different Execute methods exposed by the SqlCommand class, the most commonly used are:
ExecuteNonQuery: Executes a query and returns no result from the query (it does return the rows affected as its return value however)
ExecuteScalar: Executes a query and returns the value in the first column of the first row
ExecuteReader: Executes a query and returns the data to a SqlDataReader
Your are missing
cmd.ExecuteScalar();
You may also reuse you SqlConnection, you can open the connection right after the using (SqlConnection cn = new Sql... statement. You don't have to close the connection when the SqlConnection is in a using block, accordning to the documentation the connection is closed when you are leaving the using block.
I am trying to access a stored procedure and I'm getting an error that says:
Procedure or function 'getbug' expects parameter '#bugID', which was not supplied.
This is my code to call the procedure.
SqlCommand cmd = new SqlCommand("getbug", cn);
cmd.Parameters.Add(new SqlParameter("bugID", bugID));
bugID is set as 1089 (and is type int)
I can't figure out why this won't work.
Try this instead
SqlCommand cmd = new SqlCommand("getbug", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#bugID", bugID));
Try adding the "#" to the parameter
SqlCommand cmd = new SqlCommand("getbug", cn);
cmd.Parameters.Add(new SqlParameter("#bugID", bugID));
More code will help. Here's a couple of ideas though.
If you're calling a stored procedure, you need to specify the CommandType. Also, you can use the AddWithValue method to shorten your code.
using (var cn = new SqlConnection("your connection string"))
{
using (var cmd = new SqlCommand("getbug", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#bugID", bugID);
//etc...
}
}