原文地址:http://dotnet.aspx.cc/ShowDetail.aspx?id=J9UBRVER-L3VB-49M3-GOU1-Z6C2PVR6FZ3K
我把關鍵的部分取了出來,並作了相關的修改:
PictureBox1是指一個PictureBox控制項
name是varchar(50)類型 image是image類型
Private Sub InsertImage()Sub InsertImage() '把圖片插入到資料庫中
Dim MyStream As New FileStream("C:Inetpubwwwrootwin2000.gif", FileMode.Open, FileAccess.Read)
Dim buffer(MyStream.Length) As Byte
MyStream.Read(buffer, 0, MyStream.Length)
MyStream.Close()
Dim SqlConnectionString As String = "Persist Security Info=False;Data Source=.;Initial Catalog=aa;User ID=sa;Password="
Dim MyConnection As New SqlConnection(SqlConnectionString)
Dim MyCommand As New SqlCommand("INSERT INTO Photos ([name], [photo]) VALUES (@name, @image)", MyConnection)
MyCommand.Parameters.Add("@name", "test")
MyCommand.Parameters.Add("@image", buffer)
MyConnection.Open()
MyCommand.ExecuteNonQuery()
MyConnection.Close()
End Sub
Private Sub ShowImage()Sub ShowImage() '從資料庫中取出圖片
Dim SqlConnectionString As String = "Persist Security Info=False;Data Source=.;Initial Catalog=aa;User ID=sa;Password="
Dim MyConnection As New SqlConnection(SqlConnectionString)
MyConnection.Open()
Dim MyCommand As New SqlClient.SqlCommand("SELECT photo FROM Photos WHERE [name]='test'", MyConnection)
Dim buffer() As Byte = MyCommand.ExecuteScalar()
If (Not buffer Is Nothing) AndAlso (buffer.Length > 0) Then
Dim stream As New MemoryStream(buffer, 0, buffer.Length, True)
PictureBox1.Image = New Bitmap(stream)
stream.Close()
End If
MyConnection.Close()
End Sub