将dataGridView中的数据插入数据库错误

时间:2017-08-17 08:01:42

标签: c# mysql

错误是

  

{其他信息:您的SQL语法有错误;校验   与您的MySQL服务器版本对应的手册   在第1行')'附近使用的语法}

这是代码:

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
    StrQuery = "INSERT INTO 'branch1_orders' VALUES ("
        + order_num + ","
        + dataGridView2.Rows[i].Cells["number"].Value + ","
        + dataGridView2.Rows[i].Cells["price"].Value + ");";
    command.CommandText = StrQuery;
    command.ExecuteNonQuery(); //the error 
}

1 个答案:

答案 0 :(得分:0)

问题是在循环中又做了一步,因为datagradview自己添加一行

代码将是

for (int i = 0; i < (dataGridView2.Rows.Count)-1; i++)
            {
                StrQuery = "insert into branch1_orders values("
                    + order_num + ","
                    + dataGridView2.Rows[i].Cells["number"].Value + ","
                    + dataGridView2.Rows[i].Cells["price"].Value + ")";
                command.CommandText = StrQuery;
                command.ExecuteNonQuery();

                try
                {
                    command.ExecuteNonQuery();
                }
                catch (MySql.Data.MySqlClient.MySqlException e2)
                {
                    MessageBox.Show(e2.Message);
                }
            }