gpt4 book ai didi

c# - 将图像从 C# 保存到 SQL Server 数据库

转载 作者:太空宇宙 更新时间:2023-11-03 16:11:12 25 4
gpt4 key购买 nike

我正在尝试将图片保存到我的 SQL Server 数据库中,但它不起作用。

我的 Customers 表中的 Picture 列是 image 类型,我正在尝试将包含图片的字节数组传递给图片

我的代码是这样的:

SqlConnection conn = new SqlConnection("my working connection string");
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Customers", conn);

DataSet ds = new DataSet("Customers");

adapter.Fill(ds);

然后我为图像创建一个字节数组:

string path = null;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();

path = fileDialog.FileName;

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

byte[] picArray = new byte[fs.Length];
fs.Read(picArray, 0, Convert.ToInt32(fs.Length));
fs.Close();

这是我将值传递给数据库的方式:

DataRow row = ds.Tables[0].NewRow();
row["Id"] = "ID";
row["Name"] = "NAME";
row["Picture"] = picArray;
ds.Tables[0].Rows.Add(row);

adapter.Update(ds);

问题是这一行:

row["Picture"] = picArray;

它没有发送图片,但是数组有图片...

我做错了什么?谢谢

最佳答案

您是否正在使用对 DataSet 的更改来更新数据库?

SqlConnection conn = new SqlConnection("my working connection string");
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Customers", conn);

DataSet ds = new DataSet();

// Create command builder. This line automatically generates the update commands for you, so you don't
// have to provide or create your own.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(adapter);

// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

adapter.Fill(ds, "Customers");

// .... Code to fill the picArray....

DataRow row = ds.Tables[0].NewRow();
row["Id"] = "ID";
row["Name"] = "NAME";
row["Picture"] = picArray;
ds.Tables["Customers"].Rows.Add(row);

adapter.Update(ds, "Customers"); //Update the changes to the database

关于c# - 将图像从 C# 保存到 SQL Server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17376550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com