繁体   English   中英

在数据库中存储字节时出错,不允许从数据类型varchar到varbinary(max)的隐式转换

[英]Error while storing bytes in database ,Implicit conversion from data type varchar to varbinary(max) is not allowed

public void InsertMails(string From, string To, string Date, string Content, string AttachmentPath, byte[] CCD)
{
   ClassLibrary.ConnectionClass.CurrentConnection.ExecuteNonReader("Insert into RecieveDirectMails([From],[To],Date,[Content],AttachmentPath,CreationDate,LastUpdatedDate,IsReviewed,LastUpdatedBy,IsDeleted,IsLocked,LockedBy,CCD) values ('" + From + "','" + To + "','" + Date + "','" + Content + "','" + AttachmentPath + "','" + DateTime.Now + "','" + DateTime.Now + "','" + "0" + "','" + "0" + "','" + "0" + "','" + "0" + "','" + "0" + "','" + CCD+ "')");
}

我将XML文件字节存储到数据库中,但是发生了错误。

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

我做错了哪里,谁能帮助我。

在数据库中, CCD列的数据类型为varbinary(MAX)

T-SQL中的二进制值由前缀为0x的十六进制编码文字表示,如下所示:

INSERT INTO Foo ( Col ) VALUES ( 0xDEADBEEF )

但是,如果您通过代码执行此操作,请对SqlParameter使用参数化查询,以避免注入攻击:

SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO Foo ( Col ) VALUES ( @col )";
cmd.Parameters.Add("@col", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
cmd.ExecuteNonQuery();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM