mysql insert max + 1 error
本文关键字:error max insert mysql | 更新日期: 2023-09-27 18:30:11
我有一个包含数据网格的win表单,我向其中添加行,我想在数据库中插入这一行,但每一行都有自己的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();