【问题标题】:Inserting data from dataGridView to the database error将数据从 dataGridView 插入数据库错误
【发布时间】:2018-01-25 13:03:59
【问题描述】:

错误是

{附加信息:您的 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 
}

【问题讨论】:

  • 如果在 StrQuery 上设置断点,实际运行的 SQL 是什么?
  • 请添加生成的sql查询。
  • 请使用SqlParameter来防止Sql-Injection! order_num 应该是你的 PK 吗?
  • 尝试在每个 "," 前后添加一个空格,并删除 ";"在查询结束时。如果这不起作用,请尝试调试代码并检查值以查看它们是否为空。此外,我没有看到任何连接到此命令的连接。这也可能是问题所在。让我知道这些是否有帮助
  • @ChrisBint INSERT INTO 'branch1_orders' 值 (0,1,20000);并且数据保存在数据库中但出现错误

标签: c# mysql


【解决方案1】:

问题出在循环中,它会再执行一步,因为 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);
                }
            } 

【讨论】:

    猜你喜欢
    • 2012-08-09
    • 1970-01-01
    • 2017-04-07
    • 2013-03-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2013-05-07
    相关资源
    最近更新 更多