hey I'm trying to run this query:
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "','" + "(SELECT ProductId FROM Products WHERE ProductName =N'" + listBox1.Text + "')','" + listBox1.Text + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
now the command.UseSqlCommand is just running the query, but I keep getting this error:
incorrect syntax near 'intel'
(intel is the 'ProductName' (that I'm getting from here:
SELECT ProductId FROM Products WHERE ProductName =N'" + listBox1.Text + "'
Edit : this is the value of the command , (getting the 'incorrect syntax near 'intel')
INSERT INTO DisplayOrders
Values ('2', '(SELECT ProductId FROM Products WHERE ProductName =N'Intel Quad Core i5 3470 3.2Ghz 6MB Tray')','Intel Quad Core i5 3470 3.2Ghz 6MB Tray','1','900')"
As others have stated you should use Parameterised queries which will overcome this issue. But to answer your question "as-is"...
You need to double-close your single quote. Best way to see this is store into a string and debug / write to trace. Example of how to double-close query here: How to insert text with single quotation sql server 2005
As-is your query string will contain something like this:
INSERT INTO DisplayOrders Values ('1234','(SELECT ProductId FROM Products WHERE ProductName =N'Fred')'...
But it should really contain something like this (notice the '''):
INSERT INTO DisplayOrders Values ('1234','(SELECT ProductId FROM Products WHERE ProductName =N'''Fred''')'...
Otherwise you are closing the INSERT Values not the SELECT statement.
Just remove the single quotes around the SELECT statement
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "'," +
"(SELECT ProductId FROM Products WHERE ProductName =N'" + listbox.Text +"'), " +
"'" + listBox1.Text + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
But this code will fail if any of your listbox items contains a single quote.
I have read your comment about SQL Injection not been an issue here, but it is a good habit to use even for schoolworks. At least change to
string itemName = listBox1.Text.Replace("'", "''");
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "'," +
"(SELECT ProductId FROM Products WHERE ProductName =N'" + itemName +"'), " +
"'" + itemName + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
Need replace to this
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "'," + "(SELECT IdProduct FROM Products WHERE ProductName =N'" + listBox1.Text + "'),'" + listBox1.Text + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
SELECT ProductId FROM Products WHERE ProductName =N'" + listBox1.Text + "'
will return a table so it is wrong to use it inside insert statement.
instead of using this , execute this command alone then get the returned value and then execute the insert statement alone
Related
I am facing this error when I try to insert a data row in to table in ms access file.
dataTable is table I got using select * from TableName,
I got it, displayed it, made changes, now I want to replace previous one with new one. So I am going to delete all previous rows and add each row one by one from new table. But I am not able to insert any row.
I am getting this error
"Syntax error in INSERT INTO statement."
String query = "INSERT INTO [" + TableName + "] (TaskID, HTMLTopic, [Group], nKey,"
+ " nText, nImage, nSelImage, nFontName, nFontInfo, Keywords) VALUES (#TaskID,"
+ " #HTMLTopic, #Group, #nKey, #nText, #nImage, #nSelImage, #nFontName, "
+ " #nFontInfo, #Keywords)";
OleDbCommand command = new OleDbCommand(query, mdbConnection);
command.Parameters.AddWithValue("#TaskID", dataTable.Rows[0]["TaskID"]);
command.Parameters.AddWithValue("#HTMLTopic", dataTable.Rows[0]["HTMLTopic"]);
command.Parameters.AddWithValue("#Group", dataTable.Rows[0]["Group"]);
command.Parameters.AddWithValue("#nKey", dataTable.Rows[0]["nKey"]);
command.Parameters.AddWithValue("#nText", dataTable.Rows[0]["nText"]);
command.Parameters.AddWithValue("#nImage", dataTable.Rows[0]["nImage"]);
command.Parameters.AddWithValue("#nSelImage", dataTable.Rows[0]["nSelImage"]);
command.Parameters.AddWithValue("#nFontName", dataTable.Rows[0]["nFontName"]);
command.Parameters.AddWithValue("#nFontInfo", dataTable.Rows[0]["nFontInfo"]);
command.Parameters.AddWithValue("#Keywords", dataTable.Rows[0]["Keywords"]);
mdbConnection.Open();
command.ExecuteNonQuery();
mdbConnection.Close();
Edit:
Changed it just for debugging to
String query = "INSERT INTO [" + TableName + "] (TaskID, HTMLTopic, nRelative, [Group], nKey,"
+ " nText, nImage, nSelImage, nFontName, nFontInfo, Keywords) VALUES ('" + dataTable.Rows[0]["TaskID"]
+ "', '" + dataTable.Rows[0]["HTMLTopic"] + "', '" + dataTable.Rows[0]["nRelative"] + "', '" + dataTable.Rows[0]["Group"]
+ "', " + dataTable.Rows[0]["nKey"] + ", '" + dataTable.Rows[0]["nText"] + "', '" + dataTable.Rows[0]["nImage"]
+ "', '" + dataTable.Rows[0]["nSelImage"] + "', '" + dataTable.Rows[0]["nFontName"] + "', '" + dataTable.Rows[0]["nFontInfo"]
+ "', '" + dataTable.Rows[0]["Keywords"] + "')";
OleDbCommand command = new OleDbCommand(query, mdbConnection);
Debug.Print(command.CommandText);
mdbConnection.Open();
command.ExecuteNonQuery();
mdbConnection.Close();
I added some single quotes so database can understand them as string.
There looks to be a bug somewhere between the provider and the engine. It looks like the issue is with your column named nText.
I duplicated your schema in an Access 2013 db and received the same error that you did. I then started making various changes to the column names and the query. When I changed column names (appending a X to the end of each column) the INSERT worked. I then went back and started adding square brackets to other columns names. As soon as I did that for nText it worked. This query works for me in a C# console app using the Microsoft.ACE.OLEDB.12.0 oldeb provider:
String query =
"INSERT INTO [" + TableName + "] (TaskID,HTMLTopic,[Group],nKey,[nText],nImage,nSelImage,nFontName,nFontInfo,Keywords)" +
"VALUES" +
"(#TaskID,#HTMLTopic, #Group, #nKey, #nText, #nImage, #nSelImage, #nFontName,#nFontInfo, #Keywords)"
I agree with you that it shouldn't be a keyword / reserved word issue, but it sure acts like it is. NTEXT is a keyword in TSQL (SQL Server), but not Access according to https://support.microsoft.com/en-us/kb/286335.
I need to update the details in a certain row of my SQL Server CE database as the user wants requires to. But I get an error
There was an error parsing the query.[Token line number=1,Token line offset=31,Token in error=Name]
My query is:
"Update MembersTable set First Name='" + txtFirstName.Text +
"', Surname='" + txtSurname.Text +
"', Middle Name='" + txtMiddleName.Text +
"',Home Address='" + txtAddress.Text +
"',Date Of Birth='" + dtpDOB.Text +
"',Home Phone No='" + txtHomePhone.Text +
"',Mobile No='" + txtMobilePhone.Text +
"',Email='" + txtEmail.Text +
"',Profession='" + txtProfession.Text +
"',Cell Leaders Name='" + txtCellLeader.Text +
"' Where ID='" + DC.ID + "'";"
What am I doing wrong??
It appears like your column names contain spaces.
To deal with this, you'd want to enclose the column name with square brackets [ ]
"Update MembersTable set [First Name]='" + txtFirstName.Text + "',Surname='" + txtSurname.Text + "',[Middle Name]='" // ...
Am trying to insert a record into my database using a function that consists of 11 arguments as input. The function is as follows:
public int check_in_visitor(int visitor_id,String date_in, String date_out,
String time_in, int check_in, int check_out, String employer,
String vehicle_number, int manual_entrychk, String time_out)
The corresponding query for it:
String query = "insert into visitor values('"+visitor_id +"','" +
date_in + "','" + date_out + "','" + time_in + "'," + check_in +
",'" + check_out + "'," + employer + ",'" + vehicle_number + "'," +
manual_entrychk + ",'" + time_out + "')
its always giving errors like expression incorrect! Please help me solve the issue
Use SqlParameter..
That way you would avoid sql injection attack,enclosing data with ' or " & other issues..
String query = "insert into visitor values(#visitor_id,#date_in,#date_out,#time_in,#check_in,#check_out,#employer,#vehicle_number, #manual_entrychk,#time_out)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add(new SqlParameter("visitor_id", visitor_id));
command.Parameters.Add(new SqlParameter("date_in", date_in));
....
command.ExecuteNonQuery();
You are missing to close the Query String with double quotes.
String query = "insert into visitor values('"+visitor_id +"','" + date_in + "','" + date_out + "','" + time_in + "'," + check_in + ",'" + check_out + "'," + employer + ",'" + vehicle_number + "'," + manual_entrychk + ",'" + time_out + "')";
Note1 : all VARCHAR feilds should be enclosed in single quotes properly.
Note 2: all INT feilds should not be enclosed with single quotes.
Note 3: your query is open to SQL injection attaks. please use parameterised queries.
untill unless you provide the feild types its defficult to solve the problem.
use string.format. Like string query = string.Format("insert into visitor values ('{0}','{1}'...",vistor_id ...); This syntax is a lot easier to troubleshoot and avoids the string concatenations. You should also consider not using data that's not fully trusted in your query (like anirudh mentioned in his reply), if that's an option at all.
if query below doesnt help you, please tell what is the error returned?
string query = "insert into visitor values ("+visitor_id+ ","+ date_in +","+date_out
+","+time_in+","+check_in+","+check_out+","+employer+","+vehicle_number+","
+manual_entrychk+","+time_out+")";
I'm trying to insert some data into my table and that's how I try to do it
INSERT INTO OrdersDetail
Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '" + listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "'");
and I'm geting error I think my syntax is wrong, I'm use query in query to get the product id.
The columns are :
OrderId (int)
ProductId(int)
ProductName(Nvarchar)
OrderQuantity(Nvarchar)
TotalCost(NvarChar)
Thanks
You set your inside SELECT under '. Should be:
var query = "INSERT INTO OrdersDetail Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '"+ listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "')");
If for example TotalCost.Text is a numeric data type in SQL, use
"..." + OrderQuantity.TextAlign + "', " + Convert.ToDouble(TotalCost.Text) + ")";
As p.s.w.g stated: This is open for SQL injection. Replace it with a parameterized version!
I think the problem is with the first Line and your inside Select.
This should work
INSERT INTO OrdersDetail
Values ('" + OrderId.Text + "',(SELECT IdProduct FROM Products WHERE ProductName ='"+ listBox1.Text + "')," + TypeOfProductComboBox.Text + "','" + OrderQuantity.TextAlign + "','" + TotalCost.Text + "'");
The problem is that you are missing the last bracket, the query should finish with "')" instead of "'" . The initial code started with opening bracket and that is why you didn't get compile errors.
But you should not create such sql queries, use Parameters to avoid SQL injection attacks. You code is vulnerable to them.
I have a question, how to parse datetime value from Oracle to MySQL database.
I wrote this to extract a datetime from Oracle:
SELECT TO_CHAR(p1.creation_date,'DD.MM.RRRR HH24:mi:ss') AS dat_pot
FROM TABLE
then I put the result into data set, then I extract the value of date from dataset like this:
string lDat_otp = null;
if (rw_mat["dat_otp"].ToString().Length <= 0)
{
lDat_otp = "0";
}
else
{
lDat_otp = "convert(datetime,'" + rw_mat["dat_otp"] + "',4)";
}
Then I use lDat_otp in INSERT statement with some other values like this:
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
lDat_otp + ",'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
But there is an error on execute and it goes:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '26.01.2012 13:48:41',4)','100654', '0', '10')' at line 1
So help!!!
You can parse the datetime field into a DateTime struct and then create an insert into query with parameters and pass the date as parameter :
DateTime time = //Some value ...
String myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
"?date ,'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
MysqlCommand command = new MysqlCommand(query, connection);
command.Parameters.AddWithValue("?date", time);
Doing this you should not have problems with date formatting.
I strongly suggest to use parameters instead of string concatenation even for the others parameters of the query ...