c# - 参数 '@id' ,向数据库插入数据时未提供该参数

标签 c# sql sql-server database

我正在尝试根据 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 不为 null,我将调用该方法,如示例。

 if(id != 0)
 {
    int rel = AddUsers(user);
 }

最佳答案

您正在检查 id != 0,但使用 user.uid 作为 @id 的参数。 user.uid 是什么类型?并且确保它是 != null 因为如果您添加 null 作为参数值,它将被视为未提供。如果需要将 NULL 插入数据库,请使用 DbNull.Value

关于c# - 参数 '@id' ,向数据库插入数据时未提供该参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51215238/

相关文章:

c# - 在 ASP.Net Core 文档中使用 AsNoTracking

javascript - 我们可以使用 Html.Partial Helper 在 jQuery 中附加( block )HTML 吗? C# ASP.Net MVC 5

c# - 序列化为 JSON 时,RestSharp 的 AddBody 失败

mysql - SELECT 如何返回未排序的结果集?

sql - 如何从 Postgres 表中的 ltree 中删除特定标签?

mysql - 如何在 mysql 中添加总计作为最后一行?

sql-server - 在 EF4 中使用 NOLOCK 提示?

c# - 使用 C# 解析 .msg 文件

sql - 如何全范围均等地减少SQL查询的结果行数?

sql-server - IIS 到 SQL Server kerberos 身份验证问题