mysql插入最大+1错误

用户名

我有一个包含数据网格的胜利表单,我向其中添加行,并且我想将此行插入数据库中,但是每一行都有其自己的ID,因此我编写了此查询并尝试执行此操作,但是有错误,尤其是在尝试执行以下操作时在每行中插入最大ID +1,请帮助我正确编写此查询。

这是我的查询:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    OracleConnection CN = new OracleConnection(ConnectionString);
    string Query = 
           "insert into EMP_HASM_DET " +
           "(MAXID,EMPID,GHYAB,TAGMEE3,GZA) " +
           "  (SELECT 1 + coalesce((SELECT max(MAXID) FROM EMP_HASM_DET)), 1),'" + 
           this.dataGridView1.Rows[i].Cells[0].Value + "','" + 
           this.dataGridView1.Rows[i].Cells[1].Value + "','" + 
           this.dataGridView1.Rows[i].Cells[2].Value + "','" + 
           this.dataGridView1.Rows[i].Cells[3].Value + "'";
    OracleCommand cmd = new OracleCommand(Query, CN);
    CN.Open();
    cmd.ExecuteNonQuery();
    CN.Close();
}
茫然而困惑

一些想法...

  • 我在您的sql中没有看到VALUES子句,我认为这可能是问题的一部分。
  • 您将问题标记为MySQL,但是在代码示例中引用了Oracle连接……是什么?
  • 您正在打开和关闭每一行的连接。这会带来很多开销,请打开一次,发出命令,然后关闭它。

尽管与您的问题没有直接关系,但您可以考虑将代码重新格式化为使用String.Format,如下所示。它使事情更容易阅读。特别是因为您不是经常附加单引号。像我一样在您的代码中放置一个Debug.WriteLine语句,让我们知道它的输出...这可能会使您的问题更加明显,并让我们更好地帮助您。

-未测试的代码如下-

string sqlTemplate = "INSERT INTO EMP_HASM_DET(MAXID,EMPID,GHYAB,TAGMEE3,GZA) VALUES ({0}, '{1}', '{2}', '{3}', '{4}')";
string sqlSubquery = "(SELECT COALESCE(max(MAXID)+1, 1) FROM EMP_HASM_DET)";

OracleConnection CN = new OracleConnection(ConnectionString);
CN.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
  string Query = String.Format(sqlTemplate, 
        sqlSubquery,
        this.dataGridView1.Rows[i].Cells[0].Value,
        this.dataGridView1.Rows[i].Cells[1].Value,
        this.dataGridView1.Rows[i].Cells[2].Value,
        this.dataGridView1.Rows[i].Cells[3].Value);

  Debug.WriteLine(Query);

  OracleCommand cmd = new OracleCommand(Query, CN);
  cmd.ExecuteNonQuery();
}
CN.Close();

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章