How to execute 2 Sql statements with one button click - c#

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();
}

Related

Trouble inserting number with commas into database

I have a problem of inserting numbers with comma into database. It only accepts dot but i have function that only works with commas so is there any idea to solve this like converting decimal seperation from dot to comma
if (radioButton1.Checked)
{
Avance = 200;
}
else if (radioButton2.Checked)
{
Avance = 0;
}
cnx.Open();
SqlCommand cmd = cnx.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Employeur values('" + this.txt_ID.Text + "','" + this.txt_Nom.Text + "','" + this.txt_QUA.Text + "','" + this.txt_Salaire.Text + "','" + this.txt_NBRJ.Text + "','" + this.txt_HSUP.Text + "','" + this.txt_SalireHeur.Text + "','" + this.txt_Somme.Text + "','" + this.txt_Dette.Text + "','" + this.Avance + "','" + this.txt_Credit.Text + "','" + this.txt_Montant.Text + "','" + this.txt_Paye.Text + "','" + this.txt_Reste.Text + "')";
cmd.ExecuteNonQuery();
cnx.Close();
MessageBox.Show("Se payement est enregistrer");
You desperately need to learn how to parameterize your queries. You have several other issues going on here to. Here is a shortened version of how this query should look. Of course I would prefer to get the query out of my code entirely with a stored procedure.
cmd.CommandText = "insert into Employeur (ID, Nom) values(#txt_ID, #txt_Nom)";
cmd.Parameters.Add("#txt_ID", SqlDbType.VarChar, 30).Value = this.txt_ID.Text;
cmd.Parameters.Add("#txt_Nom", SqlDbType.VarChar, 30).value = this.txt_Nom.Text;
You would need to set the appropriate datatypes and sizes to your tables.
Also, look into the USING statement. And never just reuse a connection.
To expand on Sean's comment, the least you want is something like this:
cnx.Open();
using(SqlCommand cmd = cnx.CreateCommand()) {
cmd.CommandType = CommandType.Text;
// I've cut this down a bit to save my typing fingers - you need all your cols and values
cmd.CommandText = "insert into Employeur (Salaire) values(#Salaire)";
cmd.Parameters.Add(new SqlParameter("#Salaire", decimal.Parse(txtSalaire.Text));
cmd.ExecuteNonQuery();
}
cnx.Close();
You should also have a using around you cnx creation, but you haven't shown it above.

Query doesn't store my registration form data asp.net

I actually new in asp.net c# I want to know why this code below doesn't work.
All I want to do is store data form into a SQL Server database.
I have 2 tables and I want the data form entered stored in the database. Look at the select statement for retrieving the primary key to store it as a foreign key in the other table
String q = "Insert into dbo.requests(request_date,request_type,visit_date,reason,user_id,status_id)values('" + DateTime.Now.ToString() + "','" + DropDownList1.SelectedValue.ToString() + "','" + TextBox8.Text.ToString() + "','" + TextBox9.Text.ToString() + "','"+ 1+"','"+ 2+"')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
con.Close();
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
String a = "select top 1 request_id from dbo.requests where request_date= CAST(GETDATE() AS DATE and user_id=999 order by request_id DESC ";
SqlCommand cmd2 = new SqlCommand(a, con2);
int r = cmd2.ExecuteNonQuery();
}
con2.Close();
con3.Open();
if (con3.State == System.Data.ConnectionState.Open)
{
String b = "INSERT into dbo.visitor(visitor_Fname,visitor_Mname,visitor_family_name,visitor_id,visitor_mobile,request_id,place_of_work,country_name) values ('" + TextBox1.Text.ToString() + "','" + TextBox2.Text.ToString() + "','" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "' , '" + TextBox5.Text.ToString() + "','r', '" + TextBox6.Text.ToString() + "', '" + TextBox7.Text.ToString() + "' )";
SqlCommand cmd3 = new SqlCommand(b, con3);
cmd3.ExecuteNonQuery();
}
You should change it
int r = cmd2.ExecuteNonQuery();
to
int r = (int)cmd2.ExecuteScalar();
To retrieve selecting only one field use ExecuteScalar instead of ExecuteNonQuery. ExecuteNonQuery doesn't return selecting fields.
Just store request_id in variable using data table.
Actually you are storing 'r' in table which is wrong. Try to store request_id from select statement in variable it will be work .

incorrect syntax when I select, the error near the first name

I have a little problem with an error. but I have this command in another form and do not give me the error.
This is the code:
string select = "select CONCAT(nume,' ',prenume) from echipa where email=#EMAIL";
cmd.Connection = con;
if (bunifuCheckbox1.Checked == true)
{
con.Open();
cmd.CommandText = "Insert into clienti_fizici(nume,prenume,email,telefon,adresa,data_nasterii,data_ora,CNP,sex,judetprovenienta,temperamentclient,provenientaclient,descriere,numeagent)values('"
+ bunifuMaterialTextbox1.Text + "','" + bunifuMaterialTextbox2.Text + "','" + bunifuMaterialTextbox4.Text + "','" + bunifuMaterialTextbox8.Text + "','" + bunifuMaterialTextbox3.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss") + "','" + bunifuDatepicker1.Value.Date + "','" + bunifuMaterialTextbox11.Text + "','" + gender + "','" + bunifuMaterialTextbox12.Text + "','" + bunifuDropdown1.selectedValue + "','" + bunifuDropdown2.selectedValue
+ "','" + richTextBox1.Text + "','" + select + "')";
cmd.Parameters.AddWithValue("#EMAIL", loginform.Email);
MessageBox.Show("Datele au fost introduse in baza de date !");
cmd.ExecuteNonQuery();
con.Close();
}
and the error would be from that select.
First, you must never concatenate strings with user input to create SQL Statement. Instead, always parameterize your SQL statements. Otherwise you are risking SQL injection attacks.
Second, you can't use select inside the values clause.
What you can do add parameters or hard coded values to your select statement.
Third, SqlConnection and SqlCommand both implement the IDisposable interface and should be used as a local variable inside a using block.
A better code would look like this:
if (bunifuCheckbox1.Checked == true)
{
string sql = "Insert into clienti_fizici(nume, prenume, email, telefon, adresa, data_nasterii, data_ora, CNP, sex, judetprovenienta, temperamentclient, provenientaclient, descriere, numeagent) " +
"SELECT #nume, #prenume, #email, #telefon, #adresa, #data_nasterii, #data_ora, #CNP, #sex, #judetprovenienta, #temperamentclient, #provenientaclient, #descriere, CONCAT(nume,' ',prenume) " +
"FROM echipa where email = #EMAIL";
// Note: SqlConnection should be opened for the shortest time possible - the using statement close and dispose it when done.
using(var con = new SqlConnection(connectionString))
{
// SqlCommand is also an IDisposable and should be disposed when done.
using(var cmd = new SqlCommand(sql, con)
{
cmd.Parameters.Add("#nume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox1.Text;
cmd.Parameters.Add("#prenume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox2.Text;
//... Add the rest of the parameters here...
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar).Value = loginform.Email;
// Why is this here? MessageBox.Show("Datele au fost introduse in baza de date !");
con.Open();
cmd.ExecuteNonQuery();
}
}
}

using windows form c# to add values to Mysql database

I need to get the userid(primary key auto_increment) from another table(login) into userdetails table. When trying to run it I keep getting this error " incorrect integer value: 'LAST_INSERT_ID()' for column 'userid' at row 1".
I've tried to take LAST_INSERT_ID() out and run another query after query4 to insert the value into the userid but I can't get it to insert into the right row it just opens a new row.
this is the code am trying to run.
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;port=3310;database=e-votingsystem;username=root;password=Password12;";
//this is my insert query in which i am taking input from the user through windows forms
string Query2 = "INSERT INTO vote (username) VALUE ('" + usernameInputBox.Text + "');";
string Query3 = "INSERT INTO login (username,upassword) VALUE ('" + usernameInputBox.Text + "','" + passwordInputBox.Text + "');";
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUES ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text+"');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand3 = new MySqlCommand(Query3, MyConn2);
MySqlCommand MyCommand4 = new MySqlCommand(Query4, MyConn2);
MySqlDataReader MyReader2;
MySqlDataReader MyReader3;
MySqlDataReader MyReader4;
// opens new connection to database then executes command
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here the query will be executed and data saved into the database.
while (MyReader2.Read())
{
}
MyConn2.Close();
// opens new connection to database then executes command
MyConn2.Open();
MyReader3 = MyCommand3.ExecuteReader();
while (MyReader3.Read())
{
}
MyConn2.Close();
//opens new connection to database the exexcutes command
MyConn2.Open();
MyReader4 = MyCommand4.ExecuteReader();
while (MyReader4.Read())
{
}
MyConn2.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Hello " + forename + surname, "read and accept the terms and conditions to continue");
//new termsAndConditionsPage().Show();
//Hide();
}
As explained in other answer, you have the LAST_INSERT_ID between single quotes and this transform it in a literal string not in a statement to execute. However also removing the quotes I am not sure that you can retrieve the LAST_INSERT_ID using a connection different from the one that originates the AUTOINCREMENT number on the login table. In any case you should use a different approach and, as a first thing, you should remove ASAP the string concatenations and use parameters (Reason: Sql Injection or SurName = O'Neill)
string Query2 = "INSERT INTO vote (username) VALUE (#uname)";
string Query3 = #"INSERT INTO login (username,upassword) VALUE (#uname, #upass);
SELECT LAST_INSERT_ID();";
string Query4 = #"INSERT INTO userdetails
(nationalinsurance,userid,forename,middlename,
surname,housenumber,street,towncity,postcode,suffix)
VALUES (#insurance, #userid, #forename, #middlename,
#surname, #housenum, #street, #town, #postcode, #suffix)";
Now open just one connection and build three commands, all between an using statement
using(MySqlConnection con = new MySqlConnection(.....constring here....))
using(MySqlCommand cmd2 = new MySqlCommand(Query2, con))
using(MySqlCommand cmd3 = new MySqlCommand(Query3, con))
using(MySqlCommand cmd4 = new MySqlCommand(Query4, con))
{
con.Open();
// Add the parameter to the first command
cmd2.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
// run the first command
cmd2.ExecuteNonQuery();
// Add parameters to the second command
cmd3.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
cmd3.Parameters.Add("#upass", MySqlDbType.VarChar).Value = passwordInputBox.Text;
// Run the second command, but this one
// contains two statement, the first inserts, the
// second returns the LAST_INSERT_ID on that table, we need to
// catch that single return
int userID = (int)cmd3.ExecuteScalar();
// Run the third command
// but first prepare the parameters
cmd4.Parameters.Add("#insurance", MySqlDbType.VarChar).Value = nationalInsuranceInputBox.Text;
cmd4.Parameters.Add("#userid", MySqlDbType.Int32).Value = userID;
.... and so on for all other parameters
.... using the appropriate MySqlDbType for the column type
cmd4.ExecuteNonQuery();
}
you current query has an error
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');SELECT LAST_INSERT_ID();"
try the attached query
In your text query string you have: "','"+"LAST_INSERT_ID()"+"','". Note that the "','"s before and after the "LAST_INSERT_ID()" are incorrectly enclosing the LAST_INSERT_ID() term in single quotes.
Try the following query:
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "',"+"LAST_INSERT_ID()"+",'" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');";

How can I make these three statements more secure against SQL injection?

1.
$con = mysql_connect("localhost","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jbell2", $con);
$sql="INSERT INTO Profile (username, Date, Height, Weight, WaistSize, WeightforHeight, Blood_Pressure, Medication, Total_Cholesterol, Bad_Cholesterol, Good_Cholesterol, Triglycerides,KidneyFunctionTest)
VALUES
('$_Post[username]', '$_POST[Date]', '$_POST[Height]', '$_POST[Weight]', '$_POST[WaistSize]','$_POST[WeightforHeight]', '$_POST[Blood_Pressure]','$_POST[Medication]' ,'$_POST[Total_Cholesterol]' ,'$_POST[Bad_Cholesterol]' ,'$_POST[Good_Cholesterol]','$_POST[Triglycerides]','$_POST[KidneyFunctionTest]' )";
2
.
MySqlConnection con = new MySqlConnection("host="";user="";password=""; database="";");
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Patients(username, password, FirstName, SecondName, DiabetesType, Email,Phone, Phone2, Question1, Question2,TreatmentPlan)"
+ "values" + "('" + uname.Text + "','" + password.Text + "','" + fname.Text + "','" + lname.Text + "','" + Dtype.Text + "','" + email.Text + "','" + phone.Text + "','" + phone2.Text + "','" + q1.Text + "','" + q2.Text + "','" + treatment.Text + "')");
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
In the C# portion:
MySqlCommand cmd = new MySqlCommand("INSERT INTO Patients (username, password, FirstName,
//...
+ "values" + "('" + uname.Text + "','" + password.Text + "','" + fname.Text + "','" +
//...
+ "')");
These values should be passed in as parameters. Your command text should be built like this:
MySqlCommand cmd = new MySqlCommand("INSERT INTO Patients (username, password, FirstName,
//...
+ "values (#username, #password, #FirstName,
//...
+ "')");
Under that, you should have something like this:
cmd.Parameters.AddWithValue("username", uname.Text);
cmd.Parameters.AddWithValue("password", password.Text);
cmd.Parameters.AddWithValue("FirstName", fname.Text);
//...
If you don't, you're asking for a lot of trouble.
Dunno about PHP but in C# you can use Parameters instead of directly injecting the values.
using (MySqlConnection con = new MySqlConnection("host="";user="";password=""; database="";"))
{
con.Open();
string strSQL = "INSERT INTO Patients(username, password, FirstName, SecondName, DiabetesType, Email,Phone, Phone2, Question1, Question2,TreatmentPlan) values (?name, ?password, .....)";
using (MySqlCommand cmd = new MySqlCommand(strSQL, con))
{
cmd.Parametrs.AddWithValue("?name", fname.Text);
cmd.Parametrs.AddWithValue("?password", lname.Text);
..........
cmd.ExecuteNonQuery();
}
}
Just have ? followed by some identifier to mark that you add parameter, then use AddWithValue to insert the real value.
Also showing how to use using which dispose of the objects properly.
In first you don't have any word in SQL language.
In 2 and 3 you are creating SQL Query by concating string, this is wrong; in 2 you can use PDO to prepare PDOStatement object and execute it passing arguments securely, in second you can probably prepare this query and pass arguments but must read documentation how do this.
Read this: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
for option 2. you should definately be real escaping your strings at minimum before inserting in to DB with mysql_real_escape_string().
and you should always validate your data before inserting in to db. check you are getting the data you want, and replace any chars you should be getting.

Categories