1

I am trying to insert a record to a mysql database using c# but I always saw this error message:

You have error in your SQL syntax;check the manual that corredponds to your MySQL server version for the right syntax to use near 'Order(idOrder, Quantity, Date, Menu_idMenu)VALUES(10002, '1', '3/17/2013 12:00' at line 1

this is the code:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (!row.IsNewRow)
     {
           com.CommandText = "INSERT INTO Order (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
           int insert = com.ExecuteNonQuery();
     }
}

what does it mean?

4

2 回答 2

1

You have reserved keywords in your query, Order. Quote it and be happy.

com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";

Also, it is good practice to use parameters.

于 2013-03-16T17:50:14.390 回答
0

Date并且Order是MySQL 上的保留关键字

在之间使用它们''

com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";

并且始终使用参数化查询。这种代码对SQL 注入攻击开放。

实际上,您可以Date不带引号使用。

MySQL 允许将某些关键字用作不带引号的标识符,因为许多人以前使用过它们。

因为,我建议你使用参数化查询,在这里你可以如何在你的代码中使用它;

com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (@idOrder, @Quantity, @Date, @Menu_idMenu)";

com.Parameters.AddWithValue("@idOrder", "10002");
com.Parameters.AddWithValue("@Quantity", row.Cells[0].Value.ToString());
com.Parameters.AddWithValue("@Date", DateTime.Today.ToString());
com.Parameters.AddWithValue("@Menu_idMenu", row.Cells[1].Value.ToString());
于 2013-03-16T17:52:35.710 回答