How to save or get Images through Database.

来源:互联网 发布:exm网络用语 编辑:程序博客网 时间:2024/06/05 02:42

Recently, I see lots of friends in CSDN ask how to exchange non-text data with Database,

I looked up some materials and summary a sample . I will show you how to save or get images from SQL Server.

I hope it can give you some help.

Firstly, Create a database and a table in your SQL Server ,the table name is MyImages.

I create 3 fields in this table as follows:

1.Identity field that is named as “ID” type of int

2.Name field that is named as “Name”type of varchar

3.Image field that is named as “ImgField”type of Image

Secondly , create an C# Windows Application ,and add two buttons on the main form.

One’s name is “Save” the other’s  “Get”.

Thirdly, add the following namespace which are necessary:

Using System.Data;

Using System.Data.SqlClient;

Using System.IO;

Fourthly, add Save and Get button’s Click event

Save_Click Event:

// Database Connection String

     SqlConnection con = new SqlConnection("Server=YourServer;uid=yourName;pwd=yourpwd;database=yourdb");

SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);

SqlCommandBuilder MyCB = new SqlCommandBuilder(da);

DataSet ds = new DataSet("MyImages");

da.MissingSchemaAction = MissingSchemaAction.AddWithKey;

// Read Bitmap from file

FileStream fs = new FileStream(@"C:/winnt/Gone Your.BMP", FileMode.OpenOrCreate, FileAccess.Read);

// Put the data into byte array

byte[] MyData= new byte[fs.Length];

fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));

                       

fs.Close();            

da.Fill(ds,"MyImages");                

DataRow myRow;

// Add a new Row to DataSet

myRow=ds.Tables["MyImages"].NewRow();

myRow["Description"] = "This would be description text";

// Set Img field value

myRow["imgField"] = MyData;

// Insert a record into database

ds.Tables["MyImages"].Rows.Add(myRow);

da.Update(ds, "MyImages");

con.Close();

 

Get_Click Event:

SqlConnection con = new SqlConnection("Server=YourServer;uid=yourName;pwd=yourpwd;database=yourdb");

SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);

SqlCommandBuilder MyCB = new SqlCommandBuilder(da);

DataSet ds = new DataSet("MyImages");

byte[] MyData= new byte[0];

da.Fill(ds, "MyImages");

DataRow myRow;

myRow=ds.Tables["MyImages"].Rows[0];        

MyData =  (byte[])myRow["imgField"];

int ArraySize = new int();

ArraySize = MyData.GetUpperBound(0);

 

FileStream fs = new FileStream(@"C:/winnt/Gone Fishing2.BMP", FileMode.OpenOrCreate, FileAccess.Write);

fs.Write(MyData, 0,ArraySize);

fs.Close();

原创粉丝点击