2013-03-16 67 views
1

我想用C#中插入一条记录到MySQL数据库,但我总是看到这个错误信息的手册:错误的SQL语法;检查corredponds你的MySQL服务器

你在你的SQL有错误语法;检查对应于您的MySQL服务器版本 的手册,以便在 'Order(idOrder,Quantity,Date,Menu_idMenu)附近使用正确的语法值VALUES(10002, '1','3/17/2013 12:00 'at line 1

这是代码:

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(); 
    } 
} 

这是什么意思?

+0

_好的,这个答案没有帮助你吗? – 2013-03-16 19:21:11

回答

1

您在查询中保留了关键字Order。引用它,并开心。

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() + "')"; 

另外,最好使用参数。

0

Date and Order are reserved keywords on 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() + "')"; 
并始终 parameterized queries。这种代码打开了一个SQL Injection攻击。

其实,你可以使用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());