vb.net 存取数据库中的图片Montaque(原作)
以MS自带的数据库Northwnd为例,其中有个表是Categories,有四个四段,其中有一个是Image类型的Picture字段.我们首先添加一张bmp图片到最后一行的Picture中,然后在读出来显示到Image控件中.
添加一个SqlDataAdapter1,用向导设置联接数据库为Northwnd,SQL语句为SELECT [Category ID], [Category Name], Description, Picture FROM Categories.生成一个数据集为dataset1. 然后添加两个按钮分别表示写图片到数据库和读数据库,还有一个Image控件用于显示图片.
添加以下代码
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SqlDataAdapter1.Fill(DataSet11) End Sub
'从数据库读取图片暂时存储为monkey.bmp,然后加载到image控件里面. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadPicFromDb.Click Try Dim data As Byte() = DataSet11.Tables(0).Rows(7).Item(3) Dim myfilestream As New System.IO.FileStream(Application.StartupPath & "\monkey.bmp", IO.FileMode.Create) myfilestream.Write(data, 0, data.Length) myfilestream.Close() PictureBox1.Image = New Bitmap(Application.StartupPath & "\monkey.bmp") Catch End Try End Sub
'把C:\6.bmp写入库中,你可以改为自己的图片. Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InsertPicToDb.Click Dim myfilestream As New System.IO.FileStream("c:\6.bmp", IO.FileMode.Open) Dim data() As Byte ReDim data(myfilestream.Length - 1) myfilestream.Read(data, 0, myfilestream.Length) myfilestream.Close() DataSet11.Tables(0).Rows(7).Item(3) = data SqlDataAdapter1.Update(DataSet11.GetChanges()) End Sub
|