参数'@id',在将数据插入数据库时 未提供

问题描述 投票:2回答:1

我正在尝试根据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)
    }
}

choose data function。Never

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);
 }
c# sql sql-server database
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.