How to save combobox items in database using the insert into query? - c#

I want to save account in login database using combobox.
When I try to save, I'm presented with the error: "Syntax error in INSERT INTO statement". I tried to find the error in my INSERT INTO statement but i was unable to figure out whats wrong. This is the code I used to add items in combobox:
cmbAccountType2.DropDownStyle = ComboBoxStyle.DropDownList;
string str = null;
str = "User";
cmbAccountType2.Items.Add(str);
str = "Administrator";
cmbAccountType2.Items.Add(str);
And this is the query I used to saved the account in my login database:
private void btnSaveAccount_Click_1(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to save item?", "Confirmation", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
string q = "INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() + "')";
doSomething(q);
}
else if (result == DialogResult.No)
{
MessageBox.Show("Transaction cancelled.", "Information");
textClear();
}
loadData();
}

You have one extra comma here
"INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "'**, ,** '" + cmbAccountType2.Text.ToString() + "')";
that is the reason of error,but there are some other things you can make better in your code,
using (var cmd = new SqlCommand("INSERT INTO LoginDB (userName, password, accountType) VALUES(#name,#pw,#accType)",yourConnection))
{
cmd.Parameters.AddWithValue("name", txtUserName1.Text);
cmd.Parameters.AddWithValue("pw", txtPassword1.Text);
cmd.Parameters.AddWithValue("accType", cmbAccountType2.Text);
cmd.ExecuteNonQuery();
}
Use parametirized query
Don't use redundant ToString() methods

cmd = new SqlCommand("INSERT INTO LoginDB (userName, password, accountType) VALUES(#name,#pw,#accType)",yourConnection)
cmd.Parameters.AddWithValue("#name", txtUserName1.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword1.Text);
cmd.Parameters.AddWithValue("#accType", cmbAccountType2.SelectedItem);
cmd.ExecuteNonQuery();

txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() +
I'm not absolutely sure, but since it's a syntax error, I'm assuming this is your error.
It's part of the line where you make the query string.
string q = "INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() + "')";

Related

insert data from database to textbox C#

I have 2 textboxes and 2 labels.
label: UserID & ACCType.
textbox: Email & Password.
I want to find data from the textboxes and then insert data from the database into the 2 labels.
so, in other words, I would like to collect the email and password in the textboxes. from this information, i want to then insert the ID and AccountType in the labels. what am I doing wrong?
protected void Login_Click(object sender, EventArgs e)
{
string UID = UserID.Text;
string AType = AccType.Text;
string Email = Email.Text;
string Password = Password.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=sql2016.fse.network;Initial Catalog=db_1518393_fse_rec; User ID=user_db_1518393_fse_rec; Password=P#55word;";
Int32 verify;
string query1 = "Select * from Accounts where Email='" + Email.Text + "' and Password='" + Password.Text + "' ";
SqlCommand cmd1 = new SqlCommand(query1, con);
con.Open();
verify = Convert.ToInt32(cmd1.ExecuteScalar());
con.Close();
if (verify > 0)
{
//successful
ErrorMessage.Text += "Logging in...";
//Response.Redirect("succesful.aspx");
//display User ID & Account Type
string query2 = "INSERT * from Accounts where Email='" + Email.Text + "' and Password='" + Password.Text + "' + ID + AccountType";
//string query2 = "Select Email, Password, ID, AccountType from Accounts(Email, Password, ID, AccountType) " + "Values('" + Email + "', '" + Password + "', '" + UID + "', '" + AType + "')";
}
else
{
//unsuccessful
//Response.Redirect("unsuccesful.aspx", true);
ErrorMessage.Text += "Email or Password incorrect! Please try again.";
}
}
this is wrong
string query2 = "INSERT * from Accounts where Email='" + Email.Text + "' and Password='" + Password.Text + "' + ID + AccountType";
should be like this
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
as showing in W3Schools here
Few things to consider here...
First, as many people noticed (and always will here on SO), NEVER concatenate strings for commnand text. Instead, user parameters, like this:
string query1 = "Select * from Accounts where Email=#Email and Password=#Password ";
cmd.Parameters.Add("#Email", SqlDbType.VarChar).Value = Email.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = Password.Text;
Second, you are using ExecuteScalar which only return number of affected rows. Instead, you should read data with DataReader. Something like this:
SqlDataReader reader = cmd1.ExecuteReader();
verify = reader.HasRows;
if (verify)
{
ErrorMessage.Text += "Logging in...";
reader.Read();
this.lblUserId.Text = reader["ID"].ToString();
//read other data into other labels
}
con.Close();
third, you INSERT syntax is wrong and should be like this:
string query2 = #"
INSERT INTO Accounts
(Email, Password, ID, AccountType)
VALUES
(#Email, #Password, #ID, #AccountType)
";
cmd.Parameters.Add("#Email", SqlDbType.VarChar).Value = Email.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = Password.Text;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = /* some ID textbox or what ever */;
cmd.Parameters.Add("#AccountType", SqlDbType.Int).Value = /* some value for acc type */;
... and fourth:
why do you enter account data into table after user successfully logged in?
You said you want to update the labels after collecting email and password from the textboxes which i guess can be achieved using the 'query1', if the Account table of yours contain the field 'UserId' and 'AccountType'. You should use DataReader instead of ExecuteScalar for verification and reading of data from db and update the labels with UserId and AccountType. Following can be the hypothetical answer of yours:-
SqlDataReader dr = cmd1.ExecuteReader();
if(dr.HasRows)
{
//if email and password is okay
while(dr.Read())
{
//successful
ErrorMessage.Text += "Logging in...";
//Response.Redirect("succesful.aspx");
//display User ID & Account Type
UserId.Text = (string)dr["userid"];
AccType.Text = (string)dr["accounttype"];
}
}
else{
//unsuccessful
//Response.Redirect("unsuccesful.aspx", true);
ErrorMessage.Text += "Email or Password incorrect! Please try again.";
}
And Finally, I have no idea on why you trying to insert any data to the Account table after logging in. I mean you should update some field on your table instead of inserting a new row into the table.

Sql insert using C# - Column name or number of supplied values does not match table definition

Column name or number of supplied values does not match table definition. I'm not sure why.
public void saveToDB()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
con.Open();
string cmdtext = "Insert into tbl_user values ('" + txtname.Text + "','" + txtemail.Text + "','" + txtPassword.Text + "')";
SqlCommand cmd = new SqlCommand(cmdtext, con);
int no = cmd.ExecuteNonQuery();
if (no > 0)
{
SendEmail();
Response.Write("Register Succesfully");
}
else
{
Response.Write("Epic FAILED");
}
}
My database has:
name(varchar)
email(varchar)
password(varchar)
activated(bit)
For insert statements, if you dont insert into all the columns, (except Identity columns), you need to specify the column names, like so
string cmdtext = "Insert into tbl_user(name, email, password) values ('" + txtname.Text + "','" + txtemail.Text + "','" + txtPassword.Text + "')";
As per the comments, I neglected to let you know about best practices with SQL: check out how to prevent SQL Injection.

Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}

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