将多个图像插入SQL Server

时间:2019-04-29 16:35:28

标签: .net sql-server vb.net image insert

首先,我想指出的是,我对编程和学习仍然很陌生。

我试图通过单击一个按钮将多个图像插入到我的表中。我将图像存储在一个文件夹中,这些图像的文件名与SQL Server表中的ID列匹配。

我的表格有30列和5000行。我可以连接表格,但我不知道如何将此文件夹中的所有图像插入具有匹配ID的表格中(即,如果ID = 123456,我想将名为123456.jpg的图像文件插入到列{ {1}}。

下面是我的代码,任何帮助将不胜感激。顺便说一下,列Photo的数据类型为Photo

varbinary(max)

我尝试过:

Dim con As SqlConnection
Dim cmd As SqlCommand

Dim ds As New DataSet

con = New SqlConnection("server=MY-PC; Initial Catalog=Northwind;Integrated Security=SSPI")
cmd = New SqlCommand()
con.Open()
cmd.Connection = con

BindingSource1.DataSource = 

cmd.CommandText = "SELECT * FROM Northwind WHERE ID LIKE '" + TextBox1.Text + "'"
' dr = cmd.ExecuteReader
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)

BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1

我遇到错误

  

无法绑定到数据源上的属性或“图像”列。参数名称:dataMember

1 个答案:

答案 0 :(得分:0)

由于您正在使用绑定源,因此可以迭代列表项,将PictureBox.Image属性设置为文件中的图像,该图像也与绑定源进行数据绑定,然后更新表。否则,您将进入ByteArrays,Streams等。

    Dim BS As New BindingSource 'assumes this is bound to your table already
    PictureBox1.DataBindings.Add("Image", BS, "ImageCol")

    For Each DrowView As DataRowView In BS
        PictureBox1.Image = Image.FromFile("PathToImages\" & DrowView("NameID") & ".jpg")

        Try
            Using SqlConn As New SqlConnection("server=MY-PC; Initial Catalog=Northwind;Integrated Security=SSPI")
                Using NorthwindDA As New SqlDataAdapter("SELECT * FROM Northwind Where ID like '" + TextBox1.Text + "'", SqlConn)
                    Using NorthwindCB As New SqlCommandBuilder(NorthwindDA)
                        NorthwindDA.Update(table)
                    End Using
                End Using
            End Using
        Catch ex As Exception
            'Handle exception
        End Try

    Next