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.
Related
I have to update some values in table row if UserId = Session["username"]
but its showing error:
ExecuteNonQuery: Connection property has not been initialized.
can any one know what i am doing wrong here a Session["username"] have its value i have checked.
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration (FirstName,LastName,Password,LastName,EmaildId,UserId) " +
"VALUES (#FirstName, #LastName, #Password, #EmaildId, #UserId) WHERE UserId='" + Session["username"] + "'";
var cmd = new SqlCommand(qry);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
You need to tell the SqlCommand-object which connection to use, change this line
var cmd = new SqlCommand(qry, conn7);
Two Problems
In SQLCOMMAND you should specify querystring,connection
Your update query syntax is wrong
..try below
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration
SET FirstName=#FirstName,LastName=#LastName,Password=#Password,
EmaildId=#EmaildId,UserId=#UserId WHERE UserId=#UserId1";
var cmd = new SqlCommand(qry,conn7);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId1", Session["username"].ToString());
conn7.Open();
// cmd7.ExecuteNonQuery();
cmd.ExecuteNonQuery();
conn7.Close();
Use Parameters for all you input, don't concatenate strings in queries.
As for your error, you need to specify the connection that the command needs to use:
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;
Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = " UPDATE Registration SET FirstName = #FirstName, LastName = #LastName,"
+ " Password = #Password, EmaildId = #EmaildId WHERE UserId = #UserCondition";
var cmd = new SqlCommand(qry, conn7 );
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserCondition", Session["username"].ToString());
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
'Set' Missing
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();
}
I have an update query(stored procedure) which is working properly in SQL Server when I execute it.
CREATE PROCEDURE updatestudenthws(#stdid nvarchar(50),#hwid int, #grade float)
AS
UPDATE Table_Exercise_Answer
SET
ExAns_Grade = #grade
WHERE ExAns_Exercise = #hwid AND ExAns_Student = #stdid
but when I run the program it does not have any effect in my table and also I don't have any error.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.VarChar);
cmd.Parameters.Add("#stdid", SqlDbType.VarChar);
cmd.Parameters.Add("#grade", SqlDbType.VarChar);
cmd.Parameters["#hwid"].Value = hwid;
cmd.Parameters["#stdid"].Value = studentid;
cmd.Parameters["#grade"].Value = grade;
cmd.ExecuteNonQuery();
con.Close();
What is my mistake?
How should I do this work?
Use AddWithValue(), so you don't have to provide the type, which allowed you to make the mistake of passing varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
Your ADO.NET code defining the parameters for the stored procedure is wrong in that you don't define the parameters with their proper datatypes.
Your stored procedure defines:
#stdid nvarchar(50) --> but you define it as varchar
#hwid int --> but you define it as varchar
#grade float --> but you define it as varchar
You need to change your code to this:
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.Int); // this needs to be SqlDbType.Int
cmd.Parameters.Add("#stdid", SqlDbType.NVarChar, 50); // this should be SqlDbType.NVarChar and specify its proper length
cmd.Parameters.Add("#grade", SqlDbType.Float); // this needs to be SqlDbType.Float
when you use AddWithValue(), don't you have to provide the type passing like varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
Access 2003
VS 2010 C#
As subject title says I am having problems with. This is related to my previous question I asked, Here. I hope the mod's will be OK with this thread but I am not sure.
Martin Parkin advised not to close the connection between Insert and Select when using ##Identity with C# and MS-Access. I thought I got it working until I discovered that was not the case. To be honest I don't know how to solve this issue. So if anyone can help me I would appreciate it.
This is my btnLogin method..
cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime)";
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#LoggedInDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT #ID = ##IDENTITY";
// cmd.Parameters.AddWithValue("#ID", OleDbType.WChar); << tried this, unsuccessful
int id = (int)cmd.ExecuteScalar(); // getting the same error?
myCon.Close();
This is my btnLogOut method...
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
int id = 0;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
Close();
Or
In the btnLogin method if I do
cmd.CommandText = "SELECT #ID = ##IDENTITY";
and hide the cmd.ExecuteNonQuery(); after it. Then date and time will get logged in the database but the date and time will not get saved in the database, for logging out.
I am not sure if the problem is with btnLogin method or btnLogOut method, or both.
Working Solution
Originally I did
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate,
[LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
Then I did this
cmd.CommandText = " UPDATE [LoginLogTable] SET [UserName] = #UserName, [LoggedOutDate] =
#LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE ID = #ID";
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Parameters.AddWithValue("#ID", id);
Thanks to D Stanley and Gord Thompson.
The #ID variable does not persist in the database the way you seem to think it does. It will go out of scope when the connection is closed (possibly sooner). I would advise that you store the new identity within your application instead:
Assuming these are button handlers that are methods on the form, you could store the ID as a property of the form:
// somewhere in the form definition:
private int ID {get; set;}
...
cmd.CommandText = "SELECT ##IDENTITY";
int id = (int)cmd.ExecuteScalar();
this.ID = id;
Then use the ID in your Logout method:
// get the id from the form
int id = this.ID;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
I am using this method to insert a row into a table:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) VALUES" +
"(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
I hav also id column that have Auto Increment .
And i want to know if it possible to get the id that is created when i insert a new row.
You can access the MySqlCommand LastInsertedId property.
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) "
+ "VALUES(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
**cmd.Parameters["#clientid"].Direction = ParameterDirection.Output;**
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Basically you should add this to end of your CommandText:
SET #newPK = LAST_INSERT_ID();
and add another ADO.NET parameter "newPK". After command is executed it will contain new ID.