I am building a database using Visual Studio 2008 c# and when I'm a trying to insert a new record into my database it appears that ExecuteNonQuery has not initialized. I copy my code, hope anyone can help me in this because I am new.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.CommandText = "insert into Database1.mdf(Codigo,Nombre,Cantidad,Tipo) values('"+comboBox1.Text+"','"+textBox3.Text+"','"+textBox1.Text+"','"+comboBox2.Text+"')";
cmd.ExecuteNonQuery();
cmd.Clone();
cn.Close();
MessageBox.Show("Acabas de agregar un producto");
}
You haven't set the connection to your command:
cmd.Connection = cn;
You have numerous problems in your code:
First: The insert into statement requires a target datatable not the name of
the MDF file
Second: Employ the using statement to close and dispose the connections
Third: Parametrized query to avoid parsing problems and sql
injections
Fourth: You need to associate the connection to the command (Easily
done at the SqlCommand constructor)
using(SqlConnection cn = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand("insert into table_name(Codigo,Nombre,Cantidad,Tipo)" +
"values (#cod, #nom,#can,#tipo)", con))
{
cn.Open();
cmd.Parameters.AddWithValue("#cod", comboBox1.Text);
cmd.Parameters.AddWithValue("#nom", textBox3.Text);
cmd.Parameters.AddWithValue("#can", textBox1.Text);
cmd.Parameters.AddWithValue("#tipo", comboBox2.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Acabas de agregar un producto");
}
EDIT
The information provided by the link added by #RemusRusanu below is very important. The use of AddWithValue, whilst handy, could hinder the performance of your query. The correct approach should be the usage of a proper defined SqlParameter with both explicit datatype and parameter size.
As an example
SqlParameter p = new SqlParameter("#cod", SqlDbType.NVarChar, 255).Value = comboBox1.Text;
cmd.Parameters.Add(p);
But, of course, this requires that you check the exact datatype and size of your columns.
You did not initialize your SqlCommand with a connection. Also, you should really enclose everything here with using. And consider using parametarized commands to avoid SQL Injection.
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into databaseTableName (Codigo,Nombre,Cantidad,Tipo) values (#Codigo, #Nombre, #Cantidad, #Tipo)";
cmd.Parameters.AddWithValue("#Codigo", comboBox1.Text);
cmd.Parameters.AddWithValue("#Nombre", textBox3.Text);
cmd.Parameters.AddWithValue("#Cantidad", textBox1.Text);
cmd.Parameters.AddWithValue("#Tipo", comboBox2.Text);
cmd.Connection = cn; //this was where the error originated in the first place.
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Acabas de agregar un producto");
}
}
}
Related
I faced syntax error in UPDATE statement, while updating password in Access database in C#:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE into userdata(password)values('"+TextBox1.Text+"') where id=#id";
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
}
It's because your SQL Query is not correct, that's not how you update data in your database. It should be like this:
query = "Update [tableName] SET [ColumnName] = 'Values', [ColumnName1] = 'Values2',...";
You should learn at least the basics of SQL syntax, more information here
And also, you shouldn't concatenate your query since it will become vulnerable for SQL Injection attack, you should at least use Parameterized Query
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE yourTableName SET [yourColumnName] = #YourFirstValue, [secondColumnName] = #YourSecondValue WHERE [columnKey] = #ID"
cmd.Parameters.AddWithValue("#YourFirstValues", textbox1.Text);
cmd.Parameters.AddWithValue("#YourSecondValue ", textbox2.Text);
cmd.Parameters.AddWithValue("#ID", textbox3.Text);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
you have to fix your query
"UPDATE userdata SET password=#password where id=#id";
and add new lines before cmd.ExecuteNonQuery()
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
I had a similar problem, it gave me a syntax error that I solved by checking the whole string and actually there was a comma too many, I don't know if this answer of mine can be useful, among other things after some time.
Hi im hoping someone would indicate what im doing wrong because it keeps giving an error at my cmd.ExecuteNonQuery();
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-UDQ3PUC\\SQLEXPRESS;Initial Catalog=DBCtuLogistics;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Address values (#ComplexNumber,#ComplexName,#Street,#Suburb,#City,#Province,#Country,#PostalCode", con);
cmd.Parameters.AddWithValue("#ComplexNumber",(textBox1.Text));
cmd.Parameters.AddWithValue("#ComplexName",(textBox6.Text));
cmd.Parameters.AddWithValue("#Street", (textBox5.Text));
cmd.Parameters.AddWithValue("#Suburb", (textBox4.Text));
cmd.Parameters.AddWithValue("#City", (textBox3.Text));
cmd.Parameters.AddWithValue("#Province", (textBox2.Text));
cmd.Parameters.AddWithValue("#Country", (textBox8.Text));
cmd.Parameters.AddWithValue("#PostalCode",(textBox7.Text));
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Successfully Created!");
It seems you missed ) after #PostalCode
SqlCommand cmd = new SqlCommand("insert into Address values (#ComplexNumber,#ComplexName,#Street,#Suburb,#City,#Province,#Country,#PostalCode)", con);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO projetablosu(basvuru_no)VALUES(#basvuru_no)";
cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);
cmd.ExecuteNonQuery();
Well, if it doesn't add the record to the database you can hardly say it works, can you?
You are missing the # in the parameter. Instead of
cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);
use
cmd.Parameters.Add("#basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;
You should also read Can we stop using AddWithValue() already?
Also, as Artem wrote in his comment, you should dispose your disposable objects. The proper way to do it is with the using statement:
using (var conn = new SqlConnection(#"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True"))
{
using (var cmd = new SqlCommand("INSERT INTO projetablosu(basvuru_no)VALUES(#basvuru_no)", conn))
{
cmd.Parameters.Add("#basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;
cmd.ExecuteNonQuery();
}
}
Also note that you can use the constructors to pass all the properties you have set manually in your code, making the code shorter and more readable.
SqlConnection conn = new SqlConnection(#"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True");
string query = "INSERT INTO projetablosu(basvuru_no)VALUES('"+textBox1.Text+"')";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.ExecuteNonQuery();
// Try This Code, This Will Definately works for u
I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}
Can anyone tell me what is the proper syntax code in using datetimepicker that would be saved directly to my Microsoft sql 2005? I'm using visual studio 2008 c#.
Here is my code:
private void button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
SqlDataAdapter dad = new SqlDataAdapter();
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = conn;
dateTimePicker1.Format = DateTimePickerFormat.Short;
string dateStr = Convert.ToString(dateTimePicker1.Text);
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro", conn);
dad.InsertCommand.Parameters.Add("#School_Name", SqlDbType.VarChar).Value = textBox1.Text;
dad.InsertCommand.Parameters.Add("#Province", SqlDbType.VarChar).Value = comboBox1.Text;
dad.InsertCommand.Parameters.Add("#City", SqlDbType.VarChar).Value = textBox2.Text;
dad.InsertCommand.Parameters.Add("#Brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.InsertCommand.Parameters.Add("#Lot_Num", SqlDbType.VarChar).Value = textBox5.Text;
dad.InsertCommand.Parameters.Add("#Area", SqlDbType.Int).Value = textBox6.Text;
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.InsertCommand.Parameters.Add("#Cenro", SqlDbType.VarChar).Value = textBox8.Text;
conn.Open();
dad.InsertCommand.ExecuteNonQuery();
conn.Close();
}
The problem here is the datetimepicker, in my sql server Mem_Date_Rec is a datetime, so whenever I try to run it and save something on my database,
dad.InsertCommand.ExecuteNonQuery();
Keeps on saying "Incorrect syntax near '#Cenro'."
Can anyone help me out here please, it would be a really great help.
I feel like you try to insert your parameter to dad.InsertCommand command not cmd command.
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
Because your dad.InsertCommand has a parameter called #Mem_Date_Rec, not cmd. I have no idea what is your cmd for exactly. It's useless this case. You can't add a parameter value in an SqlCommand that doesn't have any parameter definition.
Also use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection conn = new SqlConnection(ConnectionString))
using(SqlCommand cmd = conn.CreateCommand())
{
//
}
If you want to write a proper syntax code, you need start reading a book, articles, blogs, examples etc..
edit
You're missing something in your SQL. Change this:
> dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools
> (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec,
> Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area,
> #Mem_Date_Rec, #Cenro", conn);
To this
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro)", conn);
INSERT INTO table (columns) values (value)
you had: INSERT INTO table (columns) values (value