I got OleDbException: Syntax error in INSERT INTO statement. I think that my INSERT INTO statement is good. Parameters have good data type so it's not problem. Does someone maybe know what's the problem?
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = String.Format("INSERT INTO Employees" +
" (ID, Company, Last Name, First Name, E-mail Address, Job Title, Business Phone, Home Phone" +
", Mobile Phone, Fax NUmber, Address, City, State/Province, ZIP/Postal Code, Country/Region, Web Page, Notes)" +
" Values ('{0}', '{1}','{2}','{3}','{4}','{5}'," +
"'{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')", iD,kompanija,prezime,ime,email,
zvanje,busTelefon,telefon,mobTelefon,fax,adresa,grad,okrug,postanskiBroj,zemlja,web,beleska); zvanje,busTelefon,telefon,mobTelefon,fax,adresa,grad,okrug,postanskiBroj,zemlja,web,beleska);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Error message:
UDATE SQL:
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
string cmdText = String.Format(#"UPDATE TABLE Employees " +
"SET" +
" Company='" + kompanija + "'," +
" [Last Name]='" + prezime + "'," +
" [First Name]='" + ime + "'," +
" [E-mail Address]='" + email + "' ," +
" [Job Title]='" + zvanje +"'," +
" [Business Phone]='" + busTelefon + "'," +
" [Home Phone]='" + telefon + "'," +
" [Mobile Phone]='" + mobTelefon + "'," +
" [Fax Number]='" + fax + "'," +
" Address='" + adresa + "'," +
" City='" + grad + "'," +
" [State/Province]='" + okrug + "'," +
" [ZIP/Postal Code]='" + postanskiBroj + "'," +
" [Country/Region]='" + zemlja + "'," +
" [Web Page]='" + web + "'," +
" Notes='" + beleska + "' WHERE ID="+iD);
command.CommandText = cmdText;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
And this SQL don't work. The same error like previous.
When your fields names contain a space or other misleadings characters like the / (division operator) you need them to be enclosed in square brackets
string cmdText = #"INSERT INTO Employees
(ID, Company, [Last Name], [First Name], [E-mail Address],
.., [State/Province], ....) VALUES (....)";
Also you are not using parameters in your query. String.Format is just another type of string concatenation that cannot protect you by invalid inputs (for example, try to use a single quote in your lastname value) and cannot save your code from Sql Injection vulnerability.
You should always use parameterized queries
string cmdText = #"INSERT INTO Employees ( your_field_list_comma_sep)
VALUES (#id, #company, #lastname, #firstname,
......)";
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.Parameters.Add("#id", OleDbType.Integer).Value = iD;
cmd.Parameters.Add("#company", OleDbType.VarWChar).Value = kompanija;
cmd.Parameters.Add("#lastname", OleDbType.VarWChar).Value = prezime;
cmd.Parameters.Add("#firstname", OleDbType.VarWChar).Value = ime;
....
// add all the other parameters with their name and type
....
cmd.ExecuteNonQuery();
Related
I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
"Invalid Column Name "
Exception. The code is as follows :
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
"Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
"(" + isim + ",'" + soyisim + "','" + telefon + "'," +
"'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
"'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
"'" + current_tarih + "')";
cmd.ExecuteNonQuery();
con.Close();
You've missed a single quote here " + isim + " and it should be '" + isim + "'. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
"VALUES (#isim, #soyisim , ...)";
cmd.Parameters.AddWithValue("#isim", isim);
cmd.Parameters.AddWithValue("#soyisim", soyisim);
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#isim", SqlDbType.VarChar).Value = isim;
Can we stop using AddWithValue() already?
Here I am inserting an image in msaccess database (accdb). I am not able to figure out why this is generating expcetion. It says Error in insert into statement.
String q = #"Insert Into tblModal (ModalName, CategoryId, Gender, Type, Description, image, LastUpdated) values ('" +
txtModalName.Text + "','" + categoryId + "','" + gender + "','"+txtType.Text +"', '" + txtDescription.Text + "',#pic, '" + DateTime.Now.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(q);
cmd.Parameters.AddWithValue("#pic", Check.imageToByteArray(pictureBoxPhoto.Image));
int res;
res = br.ExecuteNonQuery(cmd);
string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province'" + prov + "'where id='" + id + "'";
error :
System.Data.SqlClient.SqlException: Incorrect syntax
can anybody cor rectify the query ?
Your missing an equal:
"',province = '" + prov + "' where id='" + id + "'";
And do not build SQL-Queries like this. Please use ADO.Net Parameter.
Equal sign is missing:
,province='" + prov + "' where id='" + id + "'";
string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province='" + prov + "'where id='" + id + "'";
You miss = after province and there is no space between prov and where !
Also in this case you are open to SqlInjection, please use SqlCommand.Parameters.
The Query should look like this.
string sql = #"Update stdrecord set firstname=#FName ,lastname=#LastName, mobile=#Mobile,
phone=#Phone,city=#City, province=#Province where id=#ID";
This will protect you from SqlInjection and also sql server will cache your query.
To using command Parameters you need to add this code to your SqlCommand
SqlCommand cmd = new SqlCommand(sql, connectionString);
cmd.Parameters.AddWithValue("#FName", fName);
cmd.Parameters.AddWithValue("#LastName", lname );
cmd.Parameters.AddWithValue("#Mobile", mob);
cmd.Parameters.AddWithValue("#Phone", phn);
cmd.Parameters.AddWithValue("#City", city);
cmd.Parameters.AddWithValue("#Province", prov);
cmd.Parameters.AddWithValue("#ID", id);
With this structure you will not have problems like this in future because you will not add + and ' non stop. Also use # when you build string this give you the possibility to write string on more than one line without using +.
Put a space before Where Clause and equal sign in province column, will get work perfectly
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.