0

我有一个包含数据网格的 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();
}
4

1 回答 1

0

A few thoughts...

  • I don't see a VALUES clause in your sql, I think that may be part of the problem.
  • You tagged the question as MySQL but you reference an Oracle connection in your code sample... which is it?
  • You are opening and closing your connection for every row. That's a lot of overhead, open it once, issue your commands, then close it.

Although not directly related to your question, you might consider reformatting your code to use String.Format as shown below. It makes things a little easier to read. Particularly because you aren't constantly appending single-quotes. Put a Debug.WriteLine statement in your code like I have and let us know what it outputs... that might make your problem much more obvious and allow us to help you better.

-- Untested code follows --

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();
于 2013-09-04T14:22:25.003 回答