c# - 将数据插入数据库时未提供参数“@id”
问题描述
我正在尝试根据 id 插入数据,并且已在参数中添加了 id,但错误仍然显示未提供 id。
public static int ExecuteNonQuery(string sql, CommandType type, params SqlParameter[] param)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
PrepareCommand(sql, conn, cmd, type, param);
return cmd.ExecuteNonQuery(); // Error here (unhandled exception)
}
}
插入数据功能
public int AddUsers(Users user)
{
int rel = 0;
string sql = "INSERT INTO Student
VALUES (@id, @groupId, @userInfo, @imagePath)";
SqlParameter[] param = {
new SqlParameter("@id", user.uid),
new SqlParameter("@groupId", user.groupId),
new SqlParameter("@userInfo",user.userInfo),
new SqlParameter("@imagePath",user.imagePath),
};
rel = SqlHelper.ExecuteNonQuery(sql, CommandType.Text, param);
return rel;
}
如果 id 不为空,例如示例,我将调用该方法。
if(id != 0)
{
int rel = AddUsers(user);
}
解决方案
您正在检查id != 0
但将user.uid
其用作@id
. 什么类型user.uid
?并确保这是!= null
因为如果您添加null
为参数值,它将被视为未提供。如果您需要将 NULL 插入数据库,请使用DbNull.Value
推荐阅读
- firebase-realtime-database - 使用 Firebase 数据库实现访问者计数
- python - PyCharm 类型提示问题:'预期类型'str',改为'TruncatingCharField''
- sql - HSQL - 根据 IF 条件在查询中添加新列
- javascript - 当我在移动设备(wordpress)中点击它时,汉堡菜单没有打开
- sql - 带有 unix 时间戳的 BigQuery PARSE_TIMESTAMP - 无法解析输入字符串
- ruby-on-rails - Rails 6 simple_form 接收哈希
- node.js - 将私有注册表与 .npmrc 一起使用
- excel - 循环时无法重复获取指定单元格中包含的值
- sql-server - 将表复制到数据库中
- windows - AWS Windows userdata powershell 不工作