【问题标题】:Cannot insert null value in varbinary(max) with error : implicit conversion from data type nvarchar to varbinary(max) is not allowed无法在 varbinary(max) 中插入空值并出现错误:不允许从数据类型 nvarchar 到 varbinary(max) 的隐式转换
【发布时间】:2017-04-25 20:03:54
【问题描述】:

我想在 varbinary(max) 中插入空值,但它返回错误。

我正在尝试使用下面的代码来保存照片,当我附加照片时,它会毫无问题地保存。当没有照片时,它会引发错误。

从数据类型 nvarchar 到 varbinary(max) 的隐式转换不是 允许。使用 CONVERT 函数运行此查询。

protected void Button3_Click(object sender, EventArgs e)
{
    newphoto pat = new newphoto();
    pat.id = id.Text;
    byte[] photo = null;
    if (Attch.HasFile)
    {
        Stream fs2 = Attch.PostedFile.InputStream;
        BinaryReader br2 = new BinaryReader(fs2);
        pat.photo = br2.ReadBytes((Int32)fs2.Length);
    }
    else
    {
        pat.photo = null;
    }
    pat.Addfile()
}

public bool Addfile()
{
    Parameters.Clear();
    Parameters.AddWithValue("@pat_id", id);
    if (photo == null)
    {
        Parameters.Add("@photo", SqlDbType.VarBinary, -1);
        Parameters["@photo"].Value = DBNull.Value;
    }
    else
    {
        Parameters.AddWithValue("@photo", photo);
    }
    return FetchNonQuery(@"insert into mr_Info (@pat_id ,@photo)" +
               " Values (@pat_id ,@photo)");
}

protected bool FetchNonQuery(string CmdQuery)
{
    bool result = false;
    using (SqlConnection myConnection = DBConnection)
    {
        SqlCommand myCommand = new SqlCommand(CmdQuery, myConnection);
        myCommand.CommandType = CommandType.Text;
        //Set Parameters       
        foreach (SqlParameter Parameter in _parameters)
        {
            myCommand.Parameters.AddWithValue(Parameter.ParameterName, Parameter.Value);
        }
        //Execute the command
        myConnection.Open();
        if (myCommand.ExecuteNonQuery() > 0)
        {
            result = true;
        }
        myConnection.Close();
    }
    return result;
}

【问题讨论】:

  • myCommand.Parameters.Add(Parameter);中尝试更改将参数添加到命令的行
  • INSERT 命令也是错误的。您将参数用于字段名称和值。你应该写 INSERT INTO (pat_id,photo) VALUES (@pat_id ,@photo)
  • 我在替换为 myCommand.Parameters.Add(Parameter); 时收到此错误; SqlParameter 已包含在另一个 SqlParameterCollection 中。

标签: c#


【解决方案1】:

这是一个由 AddWithValue 调用引起的细微错误。 (还有not the only one)。
当 AddWithValue 能够正确识别参数的类型时,您没有问题,但是当您将参数值设置为 DBNull.Value 时,该方法会尝试将其转换为字符串并且您会收到错误,因为数据字段需要一个 VARBINARY。
但是,当您构建参数列表时,您可以准确指定预期的类型,因此您可以简单地将参数传递给 Add 方法,而不是使用 AddWithValue 构建另一个参数。

foreach (SqlParameter Parameter in _parameters)
{
    myCommand.Parameters.Add(Parameter);
}

你甚至可以删除循环

myCommand.Parameters.AddRange(_parameters.ToArray());

另外,正如我在其他评论中所指出的,INSERT 命令应该写成

INSERT INTO (pat_id,photo) VALUES (@pat_id ,@photo)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多