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.
Related
When I execute a query for the population of a table I get an error on only two occurrence. In particular, when the name field has some value like this:
K'Ogladbach
Now the apostrophe causes an issue, because the query interprets this command like a new value and this is wrong.
This is my structure for the query in SQL:
string sql = #"insert into Team (name, code, shortName, squadMarketValue,
crestUrl, link_self, link_fixtures, link_players, caption)
values ('" + item.name + "', '" + item.code + "', '" +
item.shortName + "', '" + item.squadMarketValue + "', '" +
item.crestUrl + "', '" + item._links.self.href + "', '" +
item._links.fixtures.href + "', '" + item._links.players.href + "', '" +
campionato + "')";
how you can see each new value is rapresented by ' value ',
so if in the value there's a " ' " it's a problem because the query failed the table population. Hopefully, there is a solution.
Use SqlParamerterized queries rather than raw SQL. This will help prevent SQL Injection and also provide a robust solution.
SqlCommand command = new SqlCommand("INSERT INTO Team (name) VALUES (#name)", con);
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = item.name;
// Add the rest of the parameters here
command.ExecuteNonQuery(); // Execute the command
SqlParamerterized queries is the best approach
You can also replace a ' with a '' in the data
That is not a double quote - it is two single quotes
E.G. K'Ogladbach to K''Ogladbach
I have a table which I had created using Toad. This has a field called created which is going to store the date of creation, so I need to insert the date of creation from the code behind using C# and an Oracle Connection.
But I am unable to insert the date. While doing so it's throwing the exception ORA-01843: not a valid month and when I try to use the to_date function it's showing that to_date couldn't be found in the current context in Microsoft Visual Studio.
I used the following code:
DateTime dt = DateTime.Today;
.
.
.
cmd.CommandText = "insert into Employee (BADGE_ID, USER_ID, FNAME, LNAME,PLANNED_ALLOC, MANAGER, TEAM,CREATED,CREATED_BY,LAST_UPD,LAST_UPD_BY) values ( '" + bid + "', '" + uid + "', '" + fn + "', '" + ln + "', " + pa + ", '" + man + "', '" + team + "', '" + TO_DATE(dt.ToString(), "yyyy/mm/dd hh24:mi:ss") + "', '" + uid + "', '" + TO_DATE(dt.ToString(), 'yyyy/mm/dd hh24:mi:ss') + "', '" + uid + "')";
So, in this case, I would say let the database do the work. Use the GETDATE() function in your SQL statement and the server will format a full timestamp and stick it in there.
The "TO_DATE" bit is part of the PL/SQL (you've got it as part of your c# command), so it should be part of the "CommandText" string.
So you want something like this:
cmd.CommandText = "insert into Employee (BADGE_ID, USER_ID, FNAME, LNAME,PLANNED_ALLOC, MANAGER, TEAM,CREATED,CREATED_BY,LAST_UPD,LAST_UPD_BY) values ( '" + bid + "', '" + uid + "', '" + fn + "', '" + ln + "', " + pa + ", '" + man + "', '" + team + "', '" + TO_DATE(dt.ToString(), "yyyy/mm/dd hh24:mi:ss") + "', '" + uid + "', TO_DATE(dt.ToString(), 'yyyy/mm/dd hh24:mi:ss') + ', '" + uid + "')";
[Notice I've removed the " (speech marks) which takes the TO_DATE out of the actual command string].
So it's got to be in the string that's "handed" to Oracle if you see what I mean.
Kind regards,
Mike
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]='" // ...
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
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 ...