-1

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

4

3 に答える 3

2

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!

于 2013-03-24T23:16:48.137 に答える
0

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 + "'");
于 2013-03-24T23:19:53.813 に答える
0

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.

于 2013-03-24T23:28:18.373 に答える