How to save or get Images through Database.

本文介绍如何使用C#在SQL Server数据库中保存与获取图像数据。主要内容包括:创建包含图像字段的数据库表,通过C#应用程序读取文件并将其转换为字节数组存储到数据库,以及从数据库中读取图像数据并写入文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Recently, I see lots of friends in 优快云 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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值