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));
Related
I am unable to send lasted inserted autoincrement id value to another table
this is my code
i am getting error is Must declare the scalar variable "#userid".
int ID;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()", cn);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
cmd.ExecuteNonQuery();
ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
SqlCommand cmd2 = new SqlCommand("insert into sampfk values(#emailid,#address,#userid)", cn);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text);
cmd2.Parameters.AddWithValue("#userid", ID);
cn.Open();
cmd2.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
TextBox3.Text = "";
TextBox4.Text = "";
I think I got your problem.you have written
SqlCommand cmd2 = new SqlCommand("insert into sampfk values (#userid, #address, #emailid)", cn);
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text)
but executing
cmd2.ExecuteNonQuery();
you should add parameter in cmd2 not cmd like as
cmd2.Parameters.AddWithValue("#userid", ID);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text)
You can do above in single step, you should use using more and try to nest query if possible. Opening TCP connection frequently has some acknowledgement overheads.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString))
{
string query = #"INSERT INTO sampdb VALUES (#name,#phone);
INSERT INTO sampfk VALUES (SCOPE_IDENITTY(), #address, #emailid); ";
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Check the following line.
ID = Convert.ToInt32(cmd.ExecuteScalar());
If this doesn't return anything, then use a default value for ID, maybe 0.
Or add a default value in the declaration as int id = 0;
try this
using (SqlConnection cn = new SqlConnection(connectionStr))
{
string sql1 = "insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()";
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
ID = cmd.ExecuteNonQuery();
}
//ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
string sql2 = "insert into sampfk values (#userid, #address, #emailid)";
using (SqlCommand cmd = new SqlCommand(sql2, cn))
{
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
con.Dispose();
con.Close();
}
i am getting this error so often, i can't find out what's wrong in here?
con.Open();
String query = "INSERT INTO user (username,[password]) values(a,b)";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("a",textBox1.Text);
cmd1.Parameters.AddWithValue("b", textBox2.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
SqlParameters should start with # like #Name. try this:
con.Open();
String query = "INSERT INTO user (Username, [Password]) values(#Username, #Password)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#Username",textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
Read Using Variables and Parameters
Executing the below code gives me error. Column 'Username' cannot be null
Values are being passed in the variables. But I think the OdbcCommand statement is not prepared properly.
OdbcCommand cmd = new OdbcCommand
{
CommandText =
"INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(#username,#name,#email,#address,#contact_number,#html_email)",
Connection = Con
};
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#address", add);
cmd.Parameters.AddWithValue("#contact_number", contact);
cmd.Parameters.AddWithValue("#html_email", table);
billid = cmd.ExecuteScalar().ToString();
OdbcCommand does not support named parameter syntax, instead you should use a question mark placeholder:
OdbcCommand cmd = new OdbcCommand
{
CommandText =
"INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(?, ?, ?, ?, ?, ?)",
Connection = Con
};
cmd.Parameters.AddWithValue("#p1", username);
cmd.Parameters.AddWithValue("#p2", name);
cmd.Parameters.AddWithValue("#p3", email);
cmd.Parameters.AddWithValue("#p4", add);
cmd.Parameters.AddWithValue("#p5", contact);
cmd.Parameters.AddWithValue("#p6", table);
int affectedRecords = cmd.ExecuteNonQuery();
Try This:
OdbcCommand cmd = new OdbcCommand("INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(#username,#name,#email,#address,#contact_number,#html_email)",Con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#address", add);
cmd.Parameters.AddWithValue("#contact_number", contact);
cmd.Parameters.AddWithValue("#html_email", table);
billid = cmd.ExecuteNonQuery();
Use ExecuteNonQuery instead of ExecuteScalar() to execute the insert statement.
int affectedRows = cmd.ExecuteNonQuery();
You probably want to return the last inserted record Id, that's why you are using ExecuteScalar. OdbcCommand doesn't support then named parameters, so you need to use the placeholder in the query. So overall you need to change the query to this
CommandText = "INSERT INTO orders(username,name,email,address,contact_number,html_email)
VALUES(?,?,?,?,?,?) SELECT SCOPE_IDENTITY()";
Now you can use the ExecuteScalar()
billid = cmd.ExecuteScalar().ToString();
I make a program that saves and update a data from the database, I can save and read data, I can also update but the problem is, I can't select the "ID" as the index, here is my sample code using "ID" as the index,
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();
}
and here is my update code that works, but the index is the "firstname",
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE FirstName = #firstname";
//cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();`
}
It works but the problem is I can't update the "FirstName", Is there a way that I can also update the Firstname? or use the "ID" as the index? thanks
I don't know what database you are going against, however, I don't know if the OleDB is being picky on the ordinal sequence of your parameters. ie: Have you tried putting your "ID" parameter in the last position to match the actual order of the fields of your update command? I don't know if it's throwing it out.
You should add the following code after the last line of ID:
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery(); {
MessageBox.Show("Update Success!");
cn.Close();
}
con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO user(Firstname,Lastname,Email,Pass,Type)
values(#first,#last,#email,#pass,#type)",con);
cmd.Parameters.Add("#first",SqlDbType.NVarChar).Value = txtfirst.Text;
cmd.Parameters.Add("#last",SqlDbType.NVarChar).Value = txtlast.Text;
cmd.Parameters.Add("#email",SqlDbType.NVarChar).Value = txtemail.Text;
cmd.Parameters.Add("#pass",SqlDbType.NVarChar).Value = txtpass.Text;
cmd.Parameters.Add("#type",SqlDbType.NVarChar).Value = "customer";
cmd.ExecuteNonQuery();
con.Close();
what is the problem with my syntax it says "Incorrect syntax near the keyword 'user'."
you should escape the table name user with delimited identifiers,
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(#first,#last,#email,#pass,#type)",con);
SQL Server Reserved Keywords
SQL Server Delimited Identifiers
UPDATE 1
Refractor your code by
using using statement to properly dispose objects
using Try-Catch block to properly handle exceptions
code snippet:
string _connStr = "connectionString here";
string _query = "INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values (#first,#last,#email,#pass,#type)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#first", txtfirst.Text);
comm.Parameters.AddWithValue("#last", txtlast.Text);
comm.Parameters.AddWithValue("#email", txtemail.Text);
comm.Parameters.AddWithValue("#pass", txtpass.Text);
comm.Parameters.AddWithValue("#type", "customer");
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(SqlException ex)
{
// other codes here
// do something with the exception
// don't swallow it.
}
}
}
AddWithValue
Add (recommended one)
USER is a reserved keyword on SQL Server.
You should use your table name with brackets [] like;
INSERT INTO [user]
You can try like;
con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(#first,#last,#email,#pass,#type)",con);
cmd.Parameters.AddWithValue("#first", txtfirst.Text);
cmd.Parameters.AddWithValue("#last", txtlast.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#pass", txtpass.Text);
cmd.Parameters.AddWithValue("#type", "customer");
cmd.ExecuteNonQuery();
con.Close();
And also like #JW said, it is always a good approach to using them in a try-catch statement.
Best Practices of Exception Management