How to execute multiple string SQL command in C# - 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");
}

Related

An open data reader

i recieve this message when i run the action: "There is already an open DataReader associated with this Command which must be closed first."
my code is:public void UpdatePoints(string rightScore, string rightWinner)
{
cmd.CommandText = "select * from Users_Details";
cmd.Connection = connection;
connection.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int points=0;
string sql;
string hisScore = (string)rdr["lastbetscore"];
string hisWinner = (string)rdr["lastbetwinner"];
if (rightScore == hisScore)
points = points + 30;
if (rightWinner == hisWinner)
{
points = points + 20;
}
sql = "update Users_Details set lastgame_points='" + points + "', gamesplayed='" + ((int)rdr["gamesplayed"] + 1) + "',currentpoints='" + ((int)rdr["currentpoints"] + points) + "',pointsPG='" + (((int)rdr["currentpoints"] + points) / ((int)rdr["gamesplayed"] + 1)) + "' where username='" + (string)rdr["username"] + "'";
cmd.CommandText = sql;
cmd.ExecuteScalar();
}
rdr.Close();
connection.Close();
}
The error message is pretty specific about what you doing wrong. You cannot reuse the command or the connection for another command while you're reading data from it. You must firstly read all the data to some List or another data structure and then update db with each element of this List.
Also, consider to execute your statements in transaction
var transaction = connection.BeginTransaction();
...
transaction.Commit();
This will speed up your updates since transaction will be created and commited only once but other way transaction will be created implicitely on each update
You should create a new Command instance instead of reusing the old one here:
sql = "update Users_Details set lastgame_points='" + points + "', gamesplayed='" + ((int)rdr["gamesplayed"] + 1) + "',currentpoints='" + ((int)rdr["currentpoints"] + points) + "',pointsPG='" + (((int)rdr["currentpoints"] + points) / ((int)rdr["gamesplayed"] + 1)) + "' where username='" + (string)rdr["username"] + "'";
cmd.CommandText = sql;
cmd.ExecuteScalar();
In addition, read up on command parameters, formatting the sql string yourself opens you up to SQL injection attacks.

How can I remove one row from a table and insert it into another via a SQL statement?

My SQL statement works fine without the delete statement which is my problem.
I use 2 OleDbCommands to call the seperate queries.
This is my current SQL statement in C#:
string mysql = "Insert Into Completed([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "')";
string newsql = "DELETE FROM Dryers WHERE [Batch number]='"+batchNumber+"'";
This my latest failed attempt in code:
if (conn.State == ConnectionState.Open)
{
try
{
using (System.Transactions.TransactionScope tScope = new TransactionScope())
{
string batchNumber = txtBatchNumber3.Text.ToString();
string product = txtProduct3.Text.ToString();
string weight = txtWeight3.Text.ToString();
string mysql = "Insert Into Packing([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "') ";
string newsql = "DELETE * FROM Dryers WHERE [Batch number]='" + batchNumber + "'";
OleDbCommand cmd = new OleDbCommand(mysql, conn);
cmd.ExecuteNonQuery();
OleDbCommand cmd2 = new OleDbCommand(newsql, conn);
cmd2.ExecuteNonQuery();
tScope.Complete();
}
MessageBox.Show("Data saved successfuly...!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
VS2012 gives the following error:
Failed due toData type mismatch in criteria expression.
You can't do this in Access. You have to call two separate SQL strings.
Use two statements but wrap them in a transaction so it's a single unit of work.
BEGIN TRANSACTION
COMMIT
if you wanted to do it in C# then you would wrap your queries in a transaction scope.
using (System.Transactions.TransactionScope tScope = new TransactionScope())
{
//do work here
//if work is completed
tScope.Complete();
//else do nothing the using statement will dispose the scope and rollback your changes.
}
Here is a walkthrough from Microsoft about making the connection against an access database and querying using ADO.NET.
https://msdn.microsoft.com/en-us/library/ms971485.aspx

SQL Server INSERT Command doesn't insert data

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.

Error while using MySqlTransaction for multiple inserts

I have a form in windows where I am doing insert statement for header and detail.
I am using MySqlTransaction for the form. When there is no error in header and detail the transaction gets committed but when there is an error in insert query of detail then the following error comes while rollback
There is already an open DataReader associated with this Connection
which must be closed first.
Here is my code.
public string Insert_Hardening_Measures_HdrANDDtl(BL_Vessel_Hardening_Measures objHdr, List<BL_Vessel_Hardening_Measures> objDtl)
{
string success = "true";
string success1 = "";
MySqlConnection MySqlConnection1 = new MySqlConnection(strCon);
MySqlConnection1.Open();
MySqlTransaction MyTransaction = MySqlConnection1.BeginTransaction();
MySqlCommand MyCommand = new MySqlCommand();
MyCommand.Transaction = MyTransaction;
MyCommand.Connection = MySqlConnection1;
try
{
MyCommand.CommandText = "insert into hardening_measures_hdr (Hardening_Measures_Hdr_id,Month,Year) values (" + objHdr.Hardening_Measures_Hdr_id + ",'" + objHdr.Month + "','" + objHdr.Year + "')";
MyCommand.ExecuteNonQuery();
for (int i = 0; i < objDtl.Count; i++)
{
MyCommand.CommandText = "insert into hardening_measures_dtl (Hardening_Measures_Dtl_id,Hardening_Measures_Hdr_id,Hardening_Measures_Mst_id,Value) values (" + objDtl[i].Hardening_Measures_Dtl_id + "," + objDtl[i].Hardening_Measures_Hdr_id + ",'" + objDtl[i].Hardening_Measures_Mst_id + ",'" + objDtl[i].Value + "')";
MyCommand.ExecuteNonQuery();
}
MyTransaction.Commit();
MySqlConnection1.Close();
}
catch
{
MyTransaction.Rollback();
}
return success;
}
Anybody who have come through this kind of problem please suggest something

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