SQL Server INSERT Command doesn't insert data - c#

I want to insert the content of some textboxes into a SQL Server database.
This is the code I use:
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
SqlCommand InsertCommand = new SqlCommand("INSERT INTO invmgmt.Products (product_id, product_name, product_price, possible_discount, product_in_stock) VALUES ('" + Convert.ToInt32(tbAddProdID.Text) + "','" + tbAddProdName.Text + "','" + Convert.ToDouble(tbAddProdPrice.Text) + "','" + Convert.ToInt32(tbAddPblDiscount.Text) + "','" + Convert.ToInt32(tbAddInStock.Text) + "')");
myConn.Close();
If I execute that, nothing happens to the database, does anyone know what to do? I've tried some other Insert commands, but nothing wants to work.

You have to associate a connection with your command then execute your query:
InsertCommand.Connection = conn;
InsertCommand.ExecuteNonQuery();
Few other things:
Do not use string concatenation to create SQL Query. Use parameters with your query. See: SqlCommand.Parameters otherwise you are prone to SQL Injection
Enclose your connection and command object in using statement.

add the connection to your command and execute it:
SqlCommand InsertCommand = new SqlCommand("INSERT INTO invmgmt.Products (product_id, product_name, product_price, possible_discount, product_in_stock) VALUES ('" + Convert.ToInt32(tbAddProdID.Text) + "','" + tbAddProdName.Text + "','" + Convert.ToDouble(tbAddProdPrice.Text) + "','" + Convert.ToInt32(tbAddPblDiscount.Text) + "','" + Convert.ToInt32(tbAddInStock.Text) + "')",myConn);
InsertCommand.ExecuteNonQuery();

You are missing:
InsertCommand.ExecuteNonQuery();

after opening connection try code below:
string query = ..........;
SqlCommand myCommand = new SqlCommand(query, myConn);
myCommand.ExecuteNonQuery();
myConn.Close();
Note: type your query instead of dots.

ExecuteNonQuery() return the number of rows affected, so its better to check the return to handle error condition
Int32 ret = sqlcommand.ExecuteNonQuery();
if (ret <= 0)
{
enter code here
}

You have to execute the query and close your connection after this as shown below
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
string sql ="YOUR QUERY...";
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
SqlCommand InsertCommand = new SqlCommand(sql,myConn);
InsertCommand.ExecuteNonQuery();
myConn.Close();
or if you want to check if query is executed or not do this instead.
if(InsertCommand.ExecuteNonQuery()>0){ //some message or function }
the returned value are the number of rows affected by the statement.

Related

How to execute multiple string SQL command in C#

Actually I want to make the button click and execute those 2 queries in one-time manner.
string Query = "UPDATE harga_semasa SET we_buy='" + this.textBox1.Text + "',we_sell='" + this.textBox2.Text + "', idharga_semasa='" + this.label5.Text + "' WHERE type='" + this.label1.Text + "';";
string Query2 = "UPDATE harga_semasa SET we_buy='" + this.textBox3.Text + "',we_sell='" + this.textBox4.Text + "', idharga_semasa='" + this.label10.Text + "' WHERE type='" + this.label4.Text + "';";
MySqlConnection MyConn2 = new MySqlConnection(ConString);
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand1 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MyReader2 = MyCommand1.ExecuteReader();
MessageBox.Show("Data Updated");
while (MyReader2.Read())
{
}
MyConn2.Close();
How do I execute multiple with this code? I try to add some data to the existing table which is already inserted. I am newbie in C# and start to understand some of the code.
You cannot reuse the same connection with multiple MySqlDataReader objects simultaneously: https://mysqlconnector.net/troubleshooting/connection-reuse/
Since your code doesn't actually need the MySqlDataReader, a simple fix is to use ExecuteNonQuery to execute your UPDATE statements.
You should also use parameterised queries to avoid SQL injection and using statements to close the connection automatically
using (var connection = new MySqlConnection(ConString))
{
connection.Open();
using (var command = new MySqlCommand(#"UPDATE harga_semasa SET we_buy=#we_buy, we_sell=#we_sell, idharga_semasa=#idharga_semasa WHERE type=#type;", connection)
{
command.Parameters.AddWithValue("#we_buy", this.textBox1.Text);
command.Parameters.AddWithValue("#we_sell", this.textBox2.Text);
command.Parameters.AddWithValue("#idharga_semasa ", this.label5.Text);
command.Parameters.AddWithValue("#type", this.label1.Text);
// use this to run the query (without MySqlDataReader)
command.ExecuteNonQuery();
}
// execute your second query the same way here
MessageBox.Show("Data Updated");
}

What's wrong with my Insert command

I'm trying to insert data into my database using a DataGridView in C#. However when I click the save button appears the following error message:
System.Data.OleDb.OleDbException was unhandled
HResult = -2147217900
Message = Syntax error in INSERT INTO statement.
Source = Microsoft Office Access Database Engine
ErrorCode = -2147217900
Here's the code I have:
private void save_btn_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Stock.accdb");
con.Open();
for (int i = 0; i < dataGridView_insert.Rows.Count; i++)
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO product(OV,Reference,Cod_Client,Client,Qtd,Type_product,Posicion_product,) VALUES ('" + dataGridView_insert.Rows[i].Cells["OV"].Value + "','" + dataGridView_insert.Rows[i].Cells["Reference"].Value + "','" + dataGridView_insert.Rows[i].Cells["Cod_Client"].Value + "','" + dataGridView_insert.Rows[i].Cells["Client"].Value + "','" + dataGridView_insert.Rows[i].Cells["Qtd"].Value + "','" + dataGridView_insert.Rows[i].Cells["Type_product"].Value + "','" + dataGridView_insert.Rows[i].Cells["Posicion_product"].Value + " ' ", con);
cmd.ExecuteNonQuery();
}
con.Close();
}
What is wrong?
You have one stray , after Posicion_product and also you missed the closing bracket of VALUES in your insert statement. Remove it. Also you should always use parameterized queries to avoid SQL Injection:
OleDbCommand cmd = new OleDbCommand("INSERT INTO product(OV,Reference,Cod_Client,Client,Qtd,Type_product,Posicion_product) VALUES (#a,#b,#c,#d,#e,#f,#g)", con);
cmd.Parameters.AddWithValue("#a", dataGridView_insert.Rows[i].Cells["OV"].Value);
cmd.Parameters.AddWithValue("#b", dataGridView_insert.Rows[i].Cells["Reference"].Value);
cmd.Parameters.AddWithValue("#c", dataGridView_insert.Rows[i].Cells["Cod_Client"].Value);
//And continue for other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#a", SqlDbType.VarChar).Value = dataGridView_insert.Rows[i].Cells["OV"].Value;

Error - Insert data into Access database in c#

Pls, am having an error code when inserting data into Access database. It keeps saying there's sytanx error in my INSERT INTO statement. Can any one help me to solve this.
Here is the code
try {
OleDbConnection connection = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\DELL\Documents\EmployeesData.accdb;
Persist Security Info = false;");
connection.Open();
OleDbCommand cmd = new OleDbCommand("insert into EmployeeInfo (UserName, Password) values('" + UserText.Text + "', '" + PassText.Text + "')", connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Inserted");
}
catch (Exception ex)
{
MessageBox.Show("Failed" + ex.ToString());
}
Password is a keyword in MSACCESS so u need to enclosed in [] bracket
OleDbCommand cmd = new OleDbCommand("insert into EmployeeInfo ([UserName], [Password])
values('" + UserText.Text + "', '" + PassText.Text + "')", connection);
Note: always use parameterized queries to avoid SQL Injection

Error SQL INSERT INTO with Odbc Command C#

Scenario:
I want to input data from textbox into the database based on microsoft data base (.mdb)
I already searching and find good clue and my result was here.
This Code below was inside command button click event:
using (OdbcConnection conn= new OdbcConnection())
{
conn.ConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=C:\\BlaBlaBla.mdb;Uid=Admin;Pwd=;";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
And when I click the command button, I get unfriendly exception
ERROR [42S02] [Microsoft][ODBC Microsoft Access Driver] Could not find
output table 'TABLENAME'.
That happened when I insert cmd.ExecuteNonQuery. If I didn't insert that, of course nothing happens in my table target.
So what mistakes did I make in that code? What should I do?
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", myConnection))
change this into
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", Conn))
you define Conn as your connection string not "myConnection"
So i changed to OleDbConnection And My Problem Cleared,
using (OleDbConnectionconn= new OleDbConnection())
{
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\LOSERONE\Documents\DATABASE\Latihan1.mdb";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand (
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
Seems, to connected the database must same as the connection string in the properties on the targeted database.
Does anyone can tell me what is the difference OleDbConnection with OdbcConnection in .mdb database file?!
This problem is because sql connection's default database after login is not the same where your table 'TABLENAME' exists. Try to add database name before table like this:
INSERT INTO DBNAME..TABLENAME (FIELD1, FIELD2)
replace your myConnection to Conn

How to execute 2 Sql statements with one button click

I've managed to run this query using wamp.
INSERT INTO guest (guestno,familyname)
VALUES(NULL,'Damn');
INSERT INTO reservation (reservationno, guestno)
VALUES(NUll,LAST_INSERT_ID())
However If I separately execute these 2 insert statements I will have a foreign key constraint.
I think the both of them need to be executed at the same time.
My questions are:
How to incorporate this into my c# winform code?
Is it possible to have 2 insert statements on one button?
When the user presses "add reservation" I would like the two MySQl query's to be executed.
Here's my insert statement:
private void button7_Click(object sender, EventArgs e)
{
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "<insert statement>";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
reader.Read();
}
UPDATED VERSION (DOESN'T WORK)
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
Form3 f3 = new Form3();
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "insert into guest (guestno, familyname) values (null, '" + textBox6.Text + "'); insert into reservation (reservationno, guestno) values (null, LAST_INSERT_ID())";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
reader.Read();
MessageBox.Show("Added Guest Reservation Successfully");
f3.guestList();
f3.reservationList();
Updated No.3 (STILL DOESN'T WORK)
string connectionString =
"Server=localhost;" +
"Database=sad;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
dbcmd = new MySqlCommand("CreateGuestAndReservation", dbcon);
dbcmd.CommandType = CommandType.StoredProcedure;
dbcmd.Parameters.AddWithValue("familyName", "foo");
dbcmd.ExecuteNonQuery();
enter code here
You can't execute more than one statement on a given MySqlCommand.
Your best bet all around (maintainability, performance, readability) is to:
create a MySQL stored procedure for your 2 SQL statements.
call your stored proc using ExecuteNonQuery().
DELIMITER //
CREATE PROCEDURE CreateGuestAndReservation
(
IN familyName VARCHAR(255)
)
BEGIN
insert into guest (guestno, familyname)
values (null, familyName);
insert into reservation (reservationno, guestno)
values (null, LAST_INSERT_ID());
END//
DELIMITER ;
Call it from your WinForms code like this:
dbcon.Open();
cmd = new MySqlCommand("CreateGuestAndReservation", dbcon);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("?familyName", "foo");
cmd.Parameters.Add("?familyName", MySqlDbType.VarChar,255).Value = "foo";
cmd.ExecuteNonQuery();
The code below should work but I suspect you may have already tried it given that you are asking for help?
string sql = "INSERT INTO guest (guestno,familyname) VALUES(NULL,'Damn'); INSERT INTO reservation (reservationno, guestno) VALUES(NUll,LAST_INSERT_ID())";
If you need parameters, try this:
string sql = "INSERT INTO guest (guestno,familyname) VALUES(NULL,?familyName); INSERT INTO reservation (reservationno, guestno) VALUES(NUll,LAST_INSERT_ID())";
...
dbcmd.Parameters.Add("#familyName", MySqlDbType.VarChar, 80).Value = _familyName;
EDIT: You may need to run 2 insert commands. See here.
I would suggest having a way to get ids other than relying on automatic id generation like autoincrements of mysql and sql server, which are very limiting. If you use a HILO id generator you first obtain id, and then execute a couple of inserts in a single transaction no problem, since you know your parent id beforehand.
It will not solve your immediate problem, but it will help tremendeously in future with your application, especially if storing parent-children like data is going to occur often.
Try this, it will work:
private void button56_Click(object sender, EventArgs e) {
con.Open();
SqlCommand cmd = new SqlCommand("insert into stholidays values('" + dateTimePicker12.Text + "','" + dateTimePicker20.Text + "','" + dateTimePicker13.Text + "','" + mbk + "','" + dateTimePicker14.Text + "','" + dateTimePicker15.Text + "','" + lt + "','" + dateTimePicker16.Text + "','" + dateTimePicker17.Text + "','" + ebk + "','" + dateTimePicker18.Text + "','" + dateTimePicker19.Text + "','" + textBox105.Text + "','" + textBox106.Text + "','" + textBox107.Text + "','" + dd + "','" + textBox104.Text + "')", con);
SqlCommand cmd1 = new SqlCommand("insert into holidays values('" + dd + "','" + ms + "','" + day + "','" + textBox104.Text + "')", con);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
con.Close();
}

Categories