【问题标题】:How to insert data by generating the primary key automatically如何通过自动生成主键来插入数据
【发布时间】:2011-11-08 12:53:14
【问题描述】:

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

共有 17 列,第一列包含主键,第二列从 Name 开始。

我在执行 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();
}

提前致谢。

【问题讨论】:

  • “自动生成主键”。不。你将如何处理并发?如果两个用户同时请求一个密钥怎么办?您将花费大量时间重新发明轮子。拜托,看在上帝的份上和他杀死的两只小猫的份上,请使用自动编号列或解释真的清楚为什么你认为你不能使用它。

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


【解决方案1】:

您的插入语句需要更加明确。您需要指定哪些字段接收哪些值。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 那你可能没做好。这是在 Access 中影响此行为的设置或属性。
    【解决方案3】:

    实际上错误表明

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2015-01-13
      相关资源
      最近更新 更多