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