往SQL Server数据库中添加图片(VB.NET)

原文地址:http://dotnet.aspx.cc/ShowDetail.aspx?id=J9UBRVER-L3VB-49M3-GOU1-Z6C2PVR6FZ3K

我把关键的部分取了出来,并作了相关的修改:

PictureBox1是指一个PictureBox控件

name是varchar(50)类型     image是image类型

    Private 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() '从数据库中取出图片
        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 NothingAndAlso (buffer.Length > 0Then
            
Dim stream As New MemoryStream(buffer, 0, buffer.Length, True)
            PictureBox1.Image 
= New Bitmap(stream)
            stream.Close()
        
End If
        MyConnection.Close()
    
End Sub
posted @ 2004-07-23 14:59  魔豆  阅读(2809)  评论(1编辑  收藏  举报