使用VB.Net和SQL Server上传图像

问题描述 投票:-1回答:1
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim command As New SqlCommand("insert into rent(Image,Status)values(@Image,@Status)", connection)
    Dim ms As New MemoryStream
    PictureBox1.Image.Save("ms", PictureBox1.Image.RawFormat)

    command.Parameters.Add("@Image", SqlDbType.VarChar).Value = ms.ToArray
    command.Parameters.Add("@Status", SqlDbType.VarChar).Value = TextBox5.Text

    connection.Open()

    If command.ExecuteNonQuery = 1 Then
        MessageBox.Show("Successfully uploaded")
    Else
        MessageBox.Show("Not uploaded")

    End If
    connection.Close()

End Sub

我正在尝试使用Visual Studio将图像上传到我的SQL Server中;一切正常,除非我点击上传按钮,我不断收到以下错误:

我尝试了所有可能的解决方案并且没有运气,我尝试启用tcp并在SQL Server中更改ip。

sql-server vb.net
1个回答
1
投票

您获得的错误意味着您无法连接到SQL Server。确保连接字符串正确,并且没有防火墙阻止运行代码的计算机与承载SQL Server的计算机之间的连接。

但是,一旦对连接错误进行排序,您的代码仍然存在一些问题。

  • PictureBox1.Image.Save("ms", PictureBox1.Image.RawFormat)更改为PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)以将图像保存到内存流中。
  • command.Parameters.Add("@Image", SqlDbType.VarChar).Value = ms.ToArray更改为command.Parameters.Add("@Image", SqlDbType.VarBinary).Value = ms.ToArray,因为memoryStream.ToArray返回字节数组,而不是字符串。
  • 确保表中的Image列实际上是VarBinary。
  • SqlCommandSqlConnectionMemoryStream都实现了IDisposable接口,因此你应该在using语句中使用它们作为局部变量。您的代码建议您使用类级别的SqlConnecion实例。那应该改变。
  • 与数据库的所有通信都应该在try ... catch块中,因为太多无法控制的事情可能会出错(例如,网络断开连接)。

您的代码看起来应该更像这样:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim RowsEffected as int = 0
    Using Dim connection As NewSqlConnection(ConnectionString
        Using Dim command As New SqlCommand("insert into rent(Image,Status)values(@Image,@Status)", connection)
            Using Dim ms As New MemoryStream
                PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)

                command.Parameters.Add("@Image", SqlDbType.VarBinary).Value = ms.ToArray
                command.Parameters.Add("@Status", SqlDbType.VarChar).Value = TextBox5.Text
                Try
                connection.Open()
                RowsEffected = command.ExecuteNonQuery()
                End Try
                Catch Exception ex
                    MessageBox.Show("Failed to upload image:"& VbCrLf & ex.Message)
                End Catch           
            End Using 
        End Using                                         
    End Using

    If RowsEffected = 1 Then
        MessageBox.Show("Successfully uploaded")
    Else
        MessageBox.Show("Not uploaded")
    End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.