【发布时间】: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#