1
我想在varbinary(max)中插入空值,但它返回错误。无法在varbinary(max)中插入空值,但出现错误:不允许将数据类型nvarchar隐式转换为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); _ – Steve
中的命令的参数也是INSERT命令错误。您使用字段名称和值的参数。您应该写入_INSERT INTO(pat_id,photo)VALUES(@pat_id,@ photo)_ – Steve
可能重复[参数varbinary数据类型中的空值](http://stackoverflow.com/questions/18170985/null-value-in -a-parameter-varbinary-datatype) –