Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following query in c# and don't have any idea why it shows me this error:
"syntax error on INSERT INTO statement".
I use Access 2013.
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO money (price,cardnum,checknum,dateTime,employeeid) values('" + TempPrice + "','" + TempCriditNum + "','" + TempCheckNum + "','" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "','" + id + "')";
command2.ExecuteNonQuery();
connection.Close();
A few things to check
dateTime is a reserved word. Try wrapping it in square brackets -
if the type of data you are dealing with is a Date\Time then you should be wrapping the input in # signs
if your data types are not strings, do not wrap them in quotes
as pointed out by Jia Jian, you should use parameterized queries
as pointed out by HansUp, Money is also a reserved word, so wrap it in square brackets
So the query ends up looking like :
command2.CommandText = "INSERT INTO [money] (price,cardnum,checknum,[dateTime],employeeid) values(" + TempPrice + "," + TempCriditNum + "," + TempCheckNum + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + id + ")";
Your SQL statement might be prone to SQL injection. Consider using parameterized queries by adding values via the OleDbCommand.Parameters property instead of concatenating it.
An example would be:
command2.CommandText = "INSERT INTO [money] (price, cardnum, checknum, [dateTime], employeeid) values(#tempPrice, #tempCreditNum, #tempCheckNum, #dateTime, #id)";
command2.Parameters.AddRange(new OleDbParameter[] {
new OleDbParameter("#tempPrice", TempPrice),
new OleDbParameter("#tempCreditNum", TempCriditNum),
new OleDbParameter("#tempCheckNum", TempCheckNum),
new OleDbParameter("#dateTime", dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString()),
new OleDbParameter("#id", id)
});
command2.ExecuteNonQuery();
This should also solve your syntax error.
Related
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
my_con.Open();
OleDbCommand o_cmd1 = my_con.CreateCommand();
o_cmd1.CommandText = "INSERT INTO Personal_Details(Date,Time,Patient_Name,Contact_Number,Gender,Allergic_To,KCO) VALUES ('" + DateTime.Now.ToString("dd-MM-yyyy") + "','" + DateTime.Now.ToString("h:mm:ss tt") + "','" + txtPatientName.Text + "','" + txtContactNo.Text + "','" + comboBoxGender.Text + "','" + txtAllergic.Text + "','" + txtKCO.Text + "')";
int j = o_cmd1.ExecuteNonQuery();
I am getting the Syntax error in Insert Statement I don't understand what is mistake if any one help me I am really thank full.Thanks in Advance.
Date and Time are typically reserved keywords in many database systems. You should at the very least wrap them with [ ]. More preferably, if you are designing the table, change the field name to something more descriptive. For example if the Date and Time represented a reminder then you could use ReminderDate and ReminderTime so as not to interfere with reserved keywords.
And follow the parameter advice that's already been given.
Use command parameters instead of concatenating strings. Your code is open for SQL Injection attacks or in your specific case the problem may be related with invalid user input. Try to thing about this situation:
What if the txtContactNo.Text returns this string "Peter's contact is +123456" ? How does the SQL query will look then? Pay close attention to ' character.
You should ALWAYS use parametrized SQL queries no matter how good you thing your input validation is. It also has more advantages like query plan caching etc.
So in your case the code must be written like this:
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
using(my_con)
{
my_con.Open();
using(OleDbCommand o_cmd1 = my_con.CreateCommand())
{
o_cmd1.CommandText = #"
INSERT INTO Personal_Details ([Date], [Time], Patient_Name, Contact_Number, Gender, Allergic_To, KCO)
VALUES (#date, #time, #name, #contNo, #gender, #alergic, #kco)";
o_cmd1.Parameters.AddWithValue("#date", DateTime.Now.ToString("dd-MM-yyyy"));
o_cmd1.Parameters.AddWithValue("#time", DateTime.Now.ToString("h:mm:ss tt"));
o_cmd1.Parameters.AddWithValue("#name", txtPatientName.Text);
o_cmd1.Parameters.AddWithValue("#contNo", txtContactNo.Text);
o_cmd1.Parameters.AddWithValue("#gender", comboBoxGender.Text);
o_cmd1.Parameters.AddWithValue("#alergic", txtAllergic.Text);
o_cmd1.Parameters.AddWithValue("#kco", txtKCO.Text);
o_cmd1.ExecuteNonQuery();
}
}
Also make sure that you are properly disposing the connection and the command objects (by using :) the using keyword)
For more info read the docs in MSDN
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to update the values of textboxes into my SQL Server database.
The code does not show any syntax error and redirects easily to the page I'm redirecting but still database is not updating the new data in it.
conn.Open();
string str_id = Session["userid"].ToString();
int id = Convert.ToInt32(str_id);
id = Int32.Parse(str_id);
string updatequery = "Update empdata set fname='" + updatename.Text + "',education='" + updateeducation.Text + "',position='" + updateposition.Text + "',email='" + updateemail.Text + "',address='" + updateaddress.Text + "',contact='" + updatecontact.Text + "',account='" + updateaccount.Text + "',postal='" + updatepostal.Text + "',password = '" + updatepwd.Text + "' Where id = '" +id.ToString()+ "'";
SqlCommand updateinfo = new SqlCommand(updatequery, conn);
updateinfo.ExecuteNonQuery();
updateinfo.Dispose();
updationmessage.Text="<p style='color:green;'>Information updated successfully</p>";
Firstly,switch to ParameterBinding, your code is prone to sql inection (and slower)
Secondly, check the return value of ExecuteNonQuery. If it is 0, then there was no change in the database, meaning no matching id has been found
Thirdly, check if you are within a transaction where you need to commit the transaction - otherwise you will not see anything in the database.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
HI here is code snippet of C#. I am trying to generate a summary of data and display in formview in asp.net. But having a issue with this code generating error that
'Incorrect syntax near 'K12'.'
please help me out.
try
{
SqlConnection conn = new SqlConnection("server=ARSLAN- LAPI\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=OTTS; " +
"connection timeout=30");
String query = "Select * FROM dbo.";
query = query + " " + "[" + session.SelectedItem.Text + "_" + dept.SelectedItem.Text + "]";
query = query + " " + "WHERE rollNo=" + "2K12-BSCS-37";
//SqlCommand cmd = new SqlCommand(query, conn);
//SqlDataReader reader;
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, conn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dataform.DataSource = table;
dataform.Visible = true;
}
catch (SqlException ex)
{
ErrorMessage.Text="Error ::"+ ex.Message;
}
The roll number string in your where clause needs to be delimited as a string. This line query = query + " " + "WHERE rollNo=" + "2K12-BSCS-37"; should be replaced with query += " " + "WHERE rollNo=" + "'2K12-BSCS-37'"; Note the single quotes.
Better still would be to use string format to build your query, something like this:
string.Format("SELECT * FROM dbo.[{0}_{1}] WHERE rollNo = '{2}'",
session.SelectedItem.Text,
dept.SelectedItem.Text,
"2K12-BSCS-37")
And even better still would be to avoid this dangerous query altogether, since it exposes your database to numerous possible attacks. I have honestly never let users build their own table name in this fashion, so I can't even say if the SQLClient parameters would work here, though I expect they will not. I agree with previous comments that much range checking, etc. will be required to make this viable.
In the end, hopefully this is an internal application that only a select few users will ever have access to.
I've got a error which I can't understand. When I'm debugging and trying to run a insert statement, its throwing the following exception:
"There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement."
I have looked all over my code, and I can't find the mistake I've made.
This is the query and the surrounding code:
SqlConnection myCon = DBcon.getInstance().conn();
int id = gm.GetID("SELECT ListID from Indkøbsliste");
id++;
Console.WriteLine("LNr: " + listnr);
string streg = GetStregkode(navne);
Console.WriteLine("stregk :" + strege);
string navn = GetVareNavn(strege);
Console.WriteLine("navn :" + navne);
myCon.Open();
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(" + id + "," + listnr + ", '" + strege + "','" + navn + "'," + il.Antal + ", "+il.Pris+")";
Console.WriteLine(il.Antal+" Antal");
Console.WriteLine(il.Pris+" Pris");
Console.WriteLine(id + " ID");
SqlCommand com = new SqlCommand(query, myCon);
com.ExecuteNonQuery();
com.Dispose();
myCon.Close();
First of all check the connection string and confirm the database location and number of columns a table has.
Suggestion : Do not use hardcoded SQL string. Use parameterized sql statements or stored-proc.
Try parameterized way,
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris)
Values (#ListID, #ListeNr, #Stregkode, #Navn, #Antal, #Pris)"
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.Add("#ListID",System.Data.SqlDbType.Int).Value=id;
com.Parameters.Add("#ListeNr",System.Data.SqlDbType.Int).Value=listnr;
com.Parameters.Add("#Stregkode",System.Data.SqlDbType.VarChar).Value=strege ;
com.Parameters.Add("#Navn",System.Data.SqlDbType.VarChar).Value=navn ;
com.Parameters.Add("#Antal",System.Data.SqlDbType.Int).Value=il.Antal;
com.Parameters.Add("#Pris",System.Data.SqlDbType.Int).Value=il.Pris;
com.ExecuteNonQuery();
Please always use parametrized queries. This helps with errors like the one you have, and far more important protects against SQL injection (google the term, or check this blog entry - as an example).
For example, what are the actual values of strege and/or navn. Depending on that it may render your SQL statement syntactically invalid or do something worse.
It (looks like) a little more work in the beginning, but will pay off big time in the end.
Are you using danish culture settings?
In that case if il.Pris is a double or decimal it will be printed using comma, which means that your sql will have an extra comma.
Ie:
INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(33,5566, 'stegkode','somename',4, 99,44)
where 99,44 is the price.
The solution is to use parameters instead of using the values directly in you sql. See some of the other answers already explaining this.
When im trying to update the textbox values into db.It throws me an exception "Invalid syntax near (value of the txtkey.text)" Can anyone Help
SqlConnection con = new SqlConnection("server=server1;Database=testdb;User Id=dev;password=sqlad#2006");
SqlCommand com = new SqlCommand("insert into tbl_licensing(UserName,CompanyName,EmailId,LicenseKey) values ('" + txtUserName.Text + "','" + txtCompanyName.Text + "','" + txtEmailId.Text + "','"+ txtKey.Text + "'",con);
con.Open();
com.ExecuteNonQuery();
con.Close();
You have started this "values (" but you never closed it. Check again.
It will be good if you use parameterized query or stored procedure instead of directly writing query
You can check this article.
http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
You have forgotten closing bracket ) in your query
Updated code for you :
SqlCommand com = new SqlCommand("insert into
tbl_licensing(UserName,CompanyName,EmailId,LicenseKey) values ('" + txtUserName.Text + "','"
+ txtCompanyName.Text + "','" + txtEmailId.Text + "','"+ txtKey.Text + "')",con);
Your code is wrong in many ways. Use parameterized query and you will
Avoid sql injection attacks
You will
not have to escape the data entered
by user
The performance of your
queries will get better
The code will be much easier to read, understand and refactor.
The correct way to use SqlCommand with parameters is to fill the SqlCommand's Parameters collection with parameter names and values.
See MSDN documentation.