2013-06-29 83 views
2

我試圖將圖片保存到我的SQL Server數據庫中,但它不起作用。將C#中的圖像保存到SQL Server數據庫中

Customers表中的列Pictureimage型的,我試圖跟圖片上的字節數組傳遞給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(); 

這是我如何將值傳遞給d atabase:

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; 

它不發送圖片,但陣中擁有的圖片...

我在做什麼錯? 謝謝

+2

[*'ntext','text'和'圖像數據類型將在未來版本的SQL Server中刪除。避免在新的開發工作中使用這些數據類型,並計劃修改當前正在使用它們的應用程序。使用'nvarchar(max)','varchar(max)'和'varbinary(max)'代替。*](http://msdn.microsoft.com/en-us/library/ms187993.aspx) –

+0

我知道,但是這是一個給數據庫的項目,我必須照原樣使用它。所以我必須保持與圖像類型.. :(但正如我所說的問題是我如何將字節數組的值傳遞給行[「圖片」],知道此列是sql圖像類型... – user1358261

+0

這是連接的完整代碼嗎?連接和適配器調用是否都使用語句包裝? –

回答

0

是否正在更新數據庫並更改了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 
+0

我上午..因爲行[「Id」]和 行[「Name」]工作。這兩行更新到數據庫,但「row [」Picture「] = picArray;」沒有更新。所以列「圖片」保留數據庫中的NULL值。我也有SqlCommandBuilder,我忘了提及 – user1358261

0

我改正了這個問題! :D

@DanSnell說過的話讓我想到我做錯了什麼。

因爲用於連接和適配器代碼就好了,我發現的,而不是通過一個參數的字節數組包含我的形象,我經過一個null byte array

這就是爲什麼當我添加的字節數組到新行row["Picture"] = picArray;,列Picture沒有收到任何值,只是一個空值。

糾正將字節數組傳遞給我的類內部的方法解決了問題。

我沒有任何改變上面的代碼,因此它可以幫助別人誰願意保存在C#中的圖片到SQL Server數據庫

相關問題