c# - 如何在 MS SQL 中插入标识列
问题描述
我有以下代码:
SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
writeCommand.ExecuteNonQuery();
该表computers
包含一个INT idientity(1,1)
名为 的列id
。
当我运行代码时,我得到一个System.Data.SqlClient.SqlException: Incorrect syntax near ')'
. 我试图找到解决方案,但在互联网上找不到。
解决方案
对于自动递增的标识列,数据库处理 id 值,除非我错过了您尝试执行的操作。
public void DemoInsert(string ComputerName, ref int newIdentifier)
{
using (var conn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = conn })
{
cmd.CommandText = "INSERT INTO computers (ComputerName) " +
"VALUES (@ComputerName); " +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.AddWithValue("@ComputerName", ComputerName);
cn.Open();
newIdentifier = (int)cmd.ExecuteScalar();
}
}
}
推荐阅读
- html - 如何在所有方向上为 flexbox 赋予相等的边距?
- python-3.x - 我们如何在 python 中使用 youtube analytics v2 API 获取 playlistID 的每日广告印象数?
- flutter - 如何在flutter中实现shuflle动画?
- ios - 如何在 iOS 应用中播放 .oga 或 .ogg 文件?
- mysql - 需要 SSL 证书时连接到 mysql 的 JDBC 连接字符串是什么?
- c# - 从控制器 MVC 更改数据库
- android - java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 13571 列是 BEGIN retrofit_ARRAY
- javascript - 在 React JS 中,当其中一个输入字段发生更改时如何从多个输入字段中获取值
- jmeter - 当我的脚本不满足条件时,我想使 Beanshell 采样器失败
- javascript - 如何避免 WebGL 中内表面的透明度?