【问题标题】:Save Image from C# into SQL Server database将 C# 中的图像保存到 SQL Server 数据库中
【发布时间】:2013-06-26 22:13:33
【问题描述】:

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

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

我的代码是这样的:

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;

不发送图片,但是数组有图片...

我做错了什么? 谢谢

【问题讨论】:

标签: c# sql image sql-server-2008 filestream


【解决方案1】:

我纠正了这个问题! :D

@DanSnell 所说的让我想起我做错了什么。

由于连接和适配器的代码很好,我发现不是通过参数传递包含我的图像的字节数组,而是传递null byte array

这就是为什么当我将字节数组添加到新行row["Picture"] = picArray; 时,Picture 列没有收到任何值,只是一个空值。

更正将字节数组传递到我的班级内部的方式解决了这个问题。

我没有更改上面的任何代码,因此它可能对想要将图像从 C# 保存到 SQL Server 数据库中的人有所帮助

【讨论】:

    【解决方案2】:

    您是否正在使用对 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
    

    【讨论】:

    • 我是.. 因为 row["Id"] 和 row["Name"] 有效。这两行更新到数据库中,但是"row["Picture"] = picArray;"没有更新。因此,“图片”列将 NULL 值保留在数据库中。我也有SqlCommandBuilder,忘了说
    猜你喜欢
    • 2015-08-13
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    相关资源
    最近更新 更多