vb.net 存取數(shù)據(jù)庫中的圖片 montaque(原作)
以ms自帶的數(shù)據(jù)庫northwnd為例,其中有個(gè)表是categories,有四個(gè)四段,其中有一個(gè)是image類型的picture字段.我們首先添加一張bmp圖片到最后一行的picture中,然后在讀出來顯示到image控件中.
添加一個(gè)sqldataadapter1,用向?qū)гO(shè)置聯(lián)接數(shù)據(jù)庫為northwnd,sql語句為select [category id], [category name], description, picture from categories.生成一個(gè)數(shù)據(jù)集為dataset1. 然后添加兩個(gè)按鈕分別表示寫圖片到數(shù)據(jù)庫和讀數(shù)據(jù)庫,還有一個(gè)image控件用于顯示圖片.
添加以下代碼
private sub form1_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load
sqldataadapter1.fill(dataset11)
end sub
'從數(shù)據(jù)庫讀取圖片暫時(shí)存儲(chǔ)為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