1. 程式人生 > >c#向SQL Server中儲存圖片並且再從資料庫中讀取圖片

c#向SQL Server中儲存圖片並且再從資料庫中讀取圖片

前言

資料庫課程設計答辯時,老師提出瞭如果資料是圖片或者其他檔案型別的時候,頓時覺得自己做的管理系統用到的較多的就是Char型別。於是,答辯結束後,就蒐集資料學習,在查詢資料的時候發現,有的一開始並不能看懂,找到一篇文件,自己做了一個測試,然後發現出現了一點小問題,雖然從整體上來說,並不影響,但是對於初學者而言就有點頭痛了。我只是一個搬運工,頂多就是自己實際測試過,成功了才敢寫在這裡,畢竟以後的學習和工作可能會用到,可以坑別人,但是不要坑自己。

步驟

一,在SQL Server中已有資料庫中建立一個表,用來儲存圖片

示例程式碼:
use MySchool
go
if exists (select * from sysobjects where name = 'Images')
drop table Images
go
create table Images
(
BLODID int identity not null,
BLOBData image not null
)


上面MySchool是資料庫名稱,可以使用其他資料庫。建的表名稱是Images列名分別是BLODID (圖片編號)和BLOBData(圖片資料)。

二,開啟VS,建立一個WinForm應用程式。向Form1中新增一個PictureBox控制元件,再新增兩個Button控制元件,將Button1的Text屬性分別設為”儲存圖片”,”顯示圖片”。

三,在Form1的程式碼之中,首先引入名稱空間:

示例程式碼:

using System.Data.SqlClient;
using System.IO;
using System.Drawing.Imaging;

四,編寫”儲存圖片”按鈕的單擊事件,用於儲存圖片;

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string connString = "Data Source = . ;Initial Catalog =hotel;User ID=sa;Pwd=123456";//資料庫連線字串
                SqlConnection connection = new SqlConnection(connString);//建立connection物件


                string
sql = "insert into Images (BLOBData) values (@blobdata)"; SqlCommand command = new SqlCommand(sql, connection); //圖片路徑 string picturePath = @"D:\1.jpg"; //注意,這裡需要指定儲存圖片的絕對路徑和圖片? //檔案的名稱,每次必須更換圖片的名稱,這裡很為不便 //建立FileStream物件 FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read); //宣告Byte陣列 Byte[] mybyte = new byte[fs.Length]; //讀取資料 fs.Read(mybyte, 0, mybyte.Length); fs.Close(); //轉換成二進位制資料,並儲存到資料庫 SqlParameter prm = new SqlParameter ("@blobdata", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte); command.Parameters.Add(prm); //開啟資料庫連線 connection.Open(); command.ExecuteNonQuery(); connection.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }

五,編寫”顯示圖片”的單擊事件,將圖片從資料庫中讀取出來顯示在PictureBox之中。

示例程式碼:

private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string connString = "Data Source = . ;Initial Catalog =hotel;User ID=sa;Pwd=123456";//資料庫連線字串
                SqlConnection connection = new SqlConnection(connString);//建立connection物件

                //開啟資料庫連線
                connection.Open();
                //建立SQL語句
                string sql = "select BLODID,BLOBData from Images order by BLODID";
                //建立SqlCommand物件
                SqlCommand command = new SqlCommand(sql, connection);
                //建立DataAdapter物件
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
                //建立DataSet物件
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "BLOBTest");
                int c = dataSet.Tables["BLOBTest"].Rows.Count;
                if (c > 0)
                {
                    Byte[] mybyte = new byte[0];
                    mybyte = (Byte[])(dataSet.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
                    MemoryStream ms = new MemoryStream(mybyte);
                    pictureBox1.Image = Image.FromStream(ms);
                }
                connection.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

結果

圖片是放在D盤的一張卡通圖。
這裡寫圖片描述