【问题标题】:SQL primary/identity key is not autoincrementingSQL 主键/标识键不是自动递增的
【发布时间】:2018-01-21 23:01:45
【问题描述】:

您好,当我在代码中传递空值时,为什么 SQL 没有自动增加我的 Id 列,我对此感到困惑:

case GameStatus.WIN:
                gamefeed.Items.Add(String.Format("Congragulations, you rolled {0}. YOU WIN.", Sum));

                connect.Open();
                SqlCommand cmdwin = connect.CreateCommand();
                cmdwin.CommandType = CommandType.Text;
                cmdwin.CommandText = "insert into Round values('','" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";
                cmdwin.ExecuteNonQuery();
                connect.Close();

                break;

感谢您向正确方向提供任何帮助或推动!

【问题讨论】:

  • 这是什么数据库? SQL Server?
  • 微软 SQL Server 17
  • 最好使用所涉及的数据库和语言来标记它,而不是使用您使用的工具。 VIsual Studio 在这里不是一个因素。我已重新标记,因此在这些领域具有专业知识的人更有可能注意到这一点。
  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看Little Bobby Tables

标签: sql sql-server vb.net sql-server-2017


【解决方案1】:

如果您已将 Id 列定义为 Identity 列,则无需在 INSERT 语句中为 Id 列传递任何内容(甚至不需要占位符)。

cmdwin.CommandText = 
    "insert into Round values('" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";

另外,请注意连接文本值(SQL 注入)是一个非常糟糕的主意,请改用参数。

【讨论】:

  • 我刚刚收到此消息“System.Data.SqlClient.SqlException: '列名或提供的值的数量与表定义不匹配。'”
  • 请发布您的表格定义。
  • @springathing 你不需要向Identity 列传递任何值,SQL Server 会处理它;-)
  • 我必须重新创建表并在创建时设置 Identity 列才能正常工作
  • @springathing:这没有任何意义;创建表时必须定义标识列!
【解决方案2】:

正如已经说过的,您不需要将值 paas 到身份字段(自动增量)

你的 SQL 应该是

"insert into Round values('" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";

如果遇到错误

Column name or number does not match table definition

然后您要么在插入中传递更多值,然后在表 Round 中传递列。 或者 您应该尝试在插入查询中给出列的名称

—Column1 is Identity
"insert into Round(Column2, Column3, Column4, Column5) values('" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";
/*Replace Column,2,3,4,5 with your respective columns in table Round*/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2016-04-22
    • 2012-03-13
    • 2013-09-28
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多