前言
数据库课程设计答辩时,老师提出了如果数据是图片或者其他文件类型的时候,顿时觉得自己做的管理系统用到的较多的就是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属性分别设为”保存图片”,”显示图片”。
示例代码:
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);
string sql = "insert into Images (BLOBData) values (@blobdata)";
SqlCommand command = new SqlCommand(sql, connection);
string picturePath = @"D:\1.jpg";
FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
五,编写”显示图片”的单击事件,将图片从数据库中读取出来显示在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.Open();
string sql = "select BLODID,BLOBData from Images order by BLODID";
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
结果
图片是放在D盘的一张卡通图。
