【问题标题】:generating sql script for byte array insertion为字节数组插入生成sql脚本
【发布时间】:2017-02-21 05:14:33
【问题描述】:

我被要求为一组特定的操作(基本上是为电子商务门户插入产品信息)生成脚本,并执行生成的脚本。我面临的问题是我们将所有图像作为二进制数据存储在表中。现在我应该如何为此编写一个查询脚本,当我尝试以字符串的形式插入字节数组时,我得到了类型不匹配。这是我尝试过的。

//imgbyte is the byte array containing the piucture data
StringBuilder sb=new StringBuilder();
sb.AppendLine("declare @picquery as Varchar(4000)");
sb.AppendLine("set @picquery='Insert into Picture(PictureBinary) values (''"+imgbyte.ToString() +"'')'");
sb.AppendLine("exec(@picquery)");
// sb is then passed to another module where it is executed.

但是二进制数据的类型错误,插入查询失败。我究竟做错了什么。 PictureBinary 列是 VarBinary(MAX)

【问题讨论】:

  • 您是否可以选择使用准备好的语句而不是生成 SQL 字符串?如果您使用准备好的语句,那么 .NET 将为您处理转换。
  • 我必须编写脚本并做好准备。该脚本将在稍后执行。

标签: asp.net sql-server


【解决方案1】:

对于写入二进制数据,SQL Server 要求数据采用十六进制格式,并带有前导 0x。示例:

INSERT INTO images (name, image) VALUES ('photo.jpg', 0xAF03083FCE...)

通常,在与数据库交互时,您最好使用参数化查询并让 .NET 为您编写最终 SQL。它会自动将字节数组转换为正确的格式。

参数化查询

// assuming 'cn' is a SqlConnection that's already open
var commandText= "INSERT INTO Picture (PictureBinary) VALUES (@bin)";
using (var cmd = new SqlCommand(commandText, cn))
{
    cmd.Parameters.Add("@bin", SqlDbType.Binary, imgByte.Length).Value = imgByte;
    cmd.ExecuteNonQuery();
}

手动查询构建

如果出于某种原因您确实需要手动构建查询,您可以这样做:

// convert the byte array to a hex string
var hexString = BitConverter.ToString(imgByte).Replace("-", "");
var sql = string.Format("INSERT INTO Picture (PictureBinary) VALUES (0x{0})", hexString);

注意:使用BitConverter 是在 C# 中将字节转换为十六进制的许多方法之一。 Here's a great SO answer comparing performance

【讨论】:

  • 让我看看这个
  • 语法错误修复:String.Format
猜你喜欢
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 2010-12-11
  • 2017-04-27
  • 1970-01-01
  • 2012-07-18
相关资源
最近更新 更多