c# - 使用 C# 创建的图像 - 如何通过 SQL 将它们插入 BLOB

标签 c# sql blob

假设我捕获屏幕截图。有我的代码

int sWidth = 1600, sHeight = 1200;

Bitmap B_M_P = Bitmap(sWidth, sHeight);

Graphics gfx = Graphics.FromImage((Image)B_M_P);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));            

B_M_P.Save("img.jpg", ImageFormat.Jpeg);

我不想将其保存到图像中,而是希望能够将其发送到我的 SQL 或 MySQL 并将它们作为 BLOB 存储在数据库中。

我也知道 LINQ 来查询数据库。我不知道的是中间部分。

  • 什么样的数据类型将用于在 BLOB 列中插入,我的 猜猜它会是一个 Byte[] 吗?

如果它是一个'Byte',那么转换就很容易了。

ImageConverter imgc = new ImageConverter();
Byte[] temp = (byte[])imgc.ConvertTo(B_M_P,typeof(byte[]));

以便之后我可以准备我的查询

"INSERT INTO EMPLOYEE (pic) VALUES ('"+temp+"');"
  • 如果不是,那么类型是什么 & 如何转换

最佳答案

你是对的,你只需要把它变成一个字节数组。你的表的数据类型应该是 VarBinary(max) .

请注意,有一个 Image数据类型,但该数据类型将在 Microsoft SQL Server 的 future 版本中删除,因此 Microsoft 建议大家改用 VarBinary 以实现 future 的兼容性。


BLOB 和 VarBinary(max) 是一回事。来自 Understanding VARCHAR(MAX) in SQL Server 2005

To solve this problem, Microsoft introduced the VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) data types in SQL Server 2005. These data types can hold the same amount of data BLOBs can hold (2 GB) and they are stored in the same type of data pages used for other data types. When data in a MAX data type exceeds 8 KB, an over-flow page is used. SQL Server 2005 automatically assigns an over-flow indicator to the page and knows how to manipulate data rows the same way it manipulates other data types. You can declare variables of MAX data types inside a stored procedure or function and even pass them as variables. You can also use them inside string functions.

Microsoft recommend using MAX data types instead of BLOBs in SQL Server 2005. In fact, BLOBs are being deprecated in future releases of SQL Server.

我在顶部提到的 Image 数据类型是旧式 BLOB 数据类型的一个示例。


下面是代码的示例

using(var cmd = SqlCommand("INSERT INTO EMPLOYEE (pic) VALUES (@pic);", connection)
{
    cmd.Parameters.Add("@pic", temp);
    cmd.ExecuteNonQuery();
}

但是,如果您正在处理大文件,则会遇到一些陷阱,请参阅 this SO answer及其深入了解在数据库中存储大型数据对象的链接。

关于c# - 使用 C# 创建的图像 - 如何通过 SQL 将它们插入 BLOB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9437029/

相关文章:

c# - csvHelper动态加载子类

sql - 无法在 Group By 中强制转换时间戳

sql - Golang SQL 错误预期 0 个参数得到 3

c# - 确定是否在 ASP.NET 中选中了 CheckBox

c# - 使用 Task.Delay() 的成本是多少?

sql - 在 postgresql 中创建一个父项或一组父项的所有子项的表

php - 如何在 PHP 中从 MySQL 数据库下载基于 blob 的文件?

azure - Azure 是否仍然对分离的磁盘收费

java - 对位于 Azure Blob 存储中的文件运行 ffprobe

c# - 如何从两个相似但不同的方法中创建一个泛型方法?