插入和;从VB Net中检索Postgresql数据库中的图像

时间:2015-03-13 15:28:43

标签: vb.net postgresql

我想在按钮点击事件中从VB.net插入和检索Postgresql数据库中的图像。我的表有一列“图像”,数据类型为bytea。我写了下面的代码但没有获得所需的输出:

'Insert 
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Try
            Dim image1 As Byte()
            Dim FS As FileStream = New FileStream("C:\0.jpg", FileMode.Open, FileAccess.Read)
            Dim BR As BinaryReader = New BinaryReader(FS)
            Dim lg As Long = FS.Length
            Dim length As Integer = Convert.ToInt32(lg)
            image1 = BR.ReadBytes(length)
            conn.Open()
            Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(@image1)", conn)
            'Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table1 values('" & timestamp & "','" & serialno & "','" & modelname & "','0','0','0','0','0','0','0','0','0','0','0','0')", conn)
            Command.Parameters.Add(New NpgsqlParameter("@image1", NpgsqlTypes.NpgsqlDbType.Bytea))
            Command.ExecuteNonQuery()
            conn.Close()

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
'retrieve
    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Try
            conn.Open()
            Dim com As NpgsqlCommand = New NpgsqlCommand("select image from table2", conn)
            Dim reader As NpgsqlDataReader = com.ExecuteReader()

            Dim imageInBytes As Byte() = reader("image")
            Dim memoryStream As System.IO.MemoryStream = _
                New System.IO.MemoryStream(imageInBytes, False)
            Dim image As System.Drawing.Image = _
                System.Drawing.Image.FromStream(memoryStream)
            image.Save("E:\image")
            PictureBox6.Image = image
            conn.Close()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

1 个答案:

答案 0 :(得分:0)

您需要在'插入'中的参数值...更改此...

(104)Connection
reset
by
peer:
client
stopped
connection
before
send
body
completed

为此...

   Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(@image1)", conn)            
   Command.Parameters.Add(New NpgsqlParameter("image1", NpgsqlTypes.NpgsqlDbType.Bytea))

在'检索'中你需要花费长度......改变这个......

   Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(:image1)", conn)
   Dim param As NpgsqlParameter = New NpgsqlParameter("image1", NpgsqlTypes.NpgsqlDbType.Bytea)
   param.Value = image1
   Command.Parameters.Add(param)

对于类似的事情......

   Dim imageInBytes As Byte() = reader("image")
  Dim memoryStream As System.IO.MemoryStream = _
      New System.IO.MemoryStream(imageInBytes, False)
  Dim image As System.Drawing.Image = _
      System.Drawing.Image.FromStream(memoryStream)
  image.Save("E:\image")
  PictureBox6.Image = image