Update table values using cmd.Parameters.AddWithValue not working - c#

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

Related

What is the correct way of using (INSERT SELECT FROM WHERE) query in C#?

I'm making a form on C# that inserts data in a table with a where clause, but it's not working. I think the syntax of my query is the problem but I can't solve it.
This is the one that I tried that's working, but I need an insert query with a where clause.
SqlCommand addEmp = new SqlCommand("INSERT INTO tbl_Expenses " +
"(InvestedMoney,EstimatedServingCount,MealName) " +
"VALUES (#inv, #est, #mname)", conn);
addEmp.Parameters.AddWithValue("#mname", textBox1.Text);
addEmp.Parameters.AddWithValue("#inv", textBox2.Text);
addEmp.Parameters.AddWithValue("#est", textBox3.Text);
conn.Open();
addEmp.ExecuteNonQuery();
conn.Close();
I tried this code below:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Meal" +
" ExpensesID, MealName, MealPrice, ImageName, Imageblob)" +
"SELECT ExpensesID, #mname, #mprice, #imname, #img " +
"FROM tbl_Expenses" +
"WHERE MealName = '"+textBox1.Text+"'",conn);
cmd.Parameters.AddWithValue("#mname", textBox1.Text);
cmd.Parameters.AddWithValue("#mprice", textBox4.Text);
cmd.Parameters.AddWithValue("#imname", textBox1.Text);
cmd.Parameters.Add("#img", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
But I get this error:
System.Data.SqlClient.SqlException: Incorrect syntax near '='
This section is missing a space between the lines:
"from tbl_Expenses" +
"WHERE MealName = '"
so the sql code references a table named tbl_ExpensesWHERE, gives the table an alias of MealName, and then has an out-of-place =.
But you should also already know from the use of parameters elsewhere it is NOT okay to substitute textBox1.Text into the query like that. NEVER do that. Not even once. Not even for practice/learning code!
There are some other poor practices in here, but that was the worst. Here's a better pattern:
string sql = #"
INSERT into tbl_Meal
(ExpensesID,MealName,MealPrice,ImageName,Imageblob)
SELECT
ExpensesID,#mname,#mprice,#mname,#img
FROM tbl_Expenses
WHERE MealName = #mname";
using (var conn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, conn))
{
//wild guess at column types. Use actual column types/size FROM THE DATABASE
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 30).Value = textBox1.Text;
cmd.Parameters.Add("#mprice", SQlDbType.Decimal, 18, 8).Value = textBox4.Text;
//use the size of the column here, not the length of the photo
cmd.Parameters.Add("#img", SqlDbType.Image, 8000).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
}
Instead of Parameters.AddWithValue() use Parameters.Add() and also use correct datatypes, for example EstimatedServingCount seems to be an int, but however AddWithValue can not know that:
addEmp.Parameters.Add("#mname", SqlDbType.VarChar).Value = textBox1.Text;
addEmp.Parameters.Add("#inv", SqlDbType.VarChar).Value = textBox2.Text;
addEmp.Parameters.Add("#est", SqlDbType.Int).Value = textBox3.Text;

C# SQL Update CommandText and Parameters

I created a simple SQL database that has one table, tblCustomerInformation, and three columns :
FirstName,
LastName,
and Email.
I'm attempting to update it however when I run the code that I listed below the program does nothing.
It doesn't crash and give me errors it just does nothing.
I'm fairly certain that my UPDATE statement is correct. I'm not sure why this isn't working at this point.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE (FirstName = #fn)";
//cmd.Parameters.Add("#ln", SqlDbType.NVarChar);
//cmd.Parameters["#ln"].Value = txtLastName.Text;
//cmd.Parameters.Add("#em", SqlDbType.NVarChar);
//cmd.Parameters["#em"].Value = txtEmail.Text;
//cmd.Parameters.Add("#fn", SqlDbType.NVarChar);
//cmd.Parameters["#fn"].Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Use this. The arrangement of cmd.Parameters... code should not be jumbled. Base it on the arrangement in your query.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE FirstName = #fn";
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Have encountered this kind of error once.

column count does match value count at row 1 C#

I do not know why I am getting this error:
C# Code:
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=***;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO student (studentID, studentFirstName, studentLastName, studentUserName, studentPassword) VALUES (#userID, #, #FirstName, #LastName, #Username, #Password);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
It may due to me overlooking something.
Error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data
Additional information: Column count doesn't match value count at row 1
Format out your code and you'll see all the syntactic problems clearly:
string connectionString =
"datasource=localhost;port=3306;database=project;username=***;password=***;";
using (MySqlConnection connection = new MySqlConnection(connectionString)) {
connection.Open();
//DONE: keep sql readable
string sql =
#"INSERT INTO student (
studentID,
studentFirstName,
studentLastName,
studentUserName,
studentPassword)
VALUES (
#userID,
#FirstName, -- wrong # param
#LastName,
#Username,
#Password);";
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(sql)) {
cmd.CommandType = CommandType.Text; // redundant
cmd.Connection = connection;
//DONE: separate code with new lines
// wrong parameter name
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
You are adding an additional parameter in your values clause (#userID, #,
also add the "#" before user id
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
should be
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));

C# SQL Server update doesn't work

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.

C# Get insert id with Auto Increment

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.

Categories

Resources