如何通过自动生成主键来插入数据

时间:2011-11-08 12:53:14

标签: c# .net winforms ms-access ado.net

我想自动插入生成主键的数据,我不知道如何生成它

第一列包含主键有17列,第二列从名称开始。

我在执行ExecuteNonQuery()时遇到错误。

错误是:

  

查询值和目标字段的数量不同。

显然我知道为什么我得到这个错误,因为我插入16列的数据而不是17但

我不知道如何通过生成主键来插入命令。

主键列是第一个,其名称是CustomerId。

我正在使用的代码是

OleDbCommand cmd = new OleDbCommand("insert into realtimedata values('" + Name+ "','" + Symbol+ "','" + D + "','" + Green + "','" + GB + "','" + GS + "','" + GBIntraBuy + "','" + GBTR1Buy + "','" + GBTR2Buy + "','" + GBTR3Buy + "','" + GBIntraSell + "','" + GBTR1Sell + "','" + GBTR2Sell + "','" + GBTR3Sell + "','" + GRSTL + "','" + Red + "');", con);
OleDbCommand cmd1 = new OleDbCommand("select CustomerId from realtimedata where (SecSym='" + Symbol + "')order by CustomerId", con);
temp = 0;
try
{
    object count = cmd1.ExecuteScalar();
    if ((count == "") || (count == null) )
    {
        cmd.ExecuteNonQuery();
        if (temp > 0)
        {
            //MessageBox.Show("One Record Added");
        }
        else
        {
            // MessageBox.Show("Record not added");
        }
    }
}
catch
{
    // con.Close();
}

提前致谢。

3 个答案:

答案 0 :(得分:3)

您的insert语句需要更明确。您需要指定哪些字段正在接收哪些值。

"insert into realtimedata(column1, column2, ... ,columnN) values('" + Name+ "','" + Symbol+ "','" + D + "','" + Green + "','" + GB + "','" + GS + "','" + GBIntraBuy + "','" + GBTR1Buy + "','" + GBTR2Buy + "','" + GBTR3Buy + "','" + GBIntraSell + "','" + GBTR1Sell + "','" + GBTR2Sell + "','" + GBTR3Sell + "','" + GRSTL + "','" + Red + "');"

答案 1 :(得分:1)

实际上错误表明

INSERT INTO (number of fields here)
VALUES (is not equal to number here)

或者不插入主键,将其创建为AutoNumber

答案 2 :(得分:1)

在Ms Access中,在设计视图中打开表格,并将第一列设为“ AutoNum ”列

相关问题