Sql server 使用VB.Net和SQL Server上传图像
我正在尝试使用Visual Studio将图像上载到我的SQL Server中;一切正常,但当我单击“上载”按钮时,不断出现以下错误:Sql server 使用VB.Net和SQL Server上传图像,sql-server,vb.net,Sql Server,Vb.net,我正在尝试使用Visual Studio将图像上载到我的SQL Server中;一切正常,但当我单击“上载”按钮时,不断出现以下错误: 我尝试了所有可能的解决方案,但没有成功,我尝试启用tcp并更改ip,即使在SQL Server中也是如此。您遇到的错误意味着您无法连接到SQL Server。 确保连接字符串正确,并且没有防火墙阻止运行代码的计算机与承载SQL Server的计算机之间的连接 但是,一旦对连接错误进行排序,代码仍然存在一些问题 更改PictureBox1.Image.Save
我尝试了所有可能的解决方案,但没有成功,我尝试启用tcp并更改ip,即使在SQL Server中也是如此。您遇到的错误意味着您无法连接到SQL Server。 确保连接字符串正确,并且没有防火墙阻止运行代码的计算机与承载SQL Server的计算机之间的连接 但是,一旦对连接错误进行排序,代码仍然存在一些问题
- 更改
至PictureBox1.Image.Save(“ms”,PictureBox1.Image.RawFormat)
将图像保存到内存流中PictureBox1.Image.Save(ms,PictureBox1.Image.RawFormat)
- 更改
添加(“@Image”,SqlDbType.VarBinary).Value=ms.ToArray 因为memoryStream.ToArray返回的是字节数组,而不是字符串command.Parameters.Add(“@Image”,SqlDbType.VarChar).Value=ms.ToArray
- 确保表中的
列实际上是VarBinaryImage
、SqlCommand
和SqlConnection
都实现了MemoryStream
接口,因此您应该在IDisposable
语句中将它们全部用作局部变量。您的代码表明您正在使用类级别的using
实例。这应该改变SqlConnecion
- 所有与数据库的通信都应该在try…catch块中,因为太多您无法控制的事情可能会出错(例如,网络断开)
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
(如果此问题与代码无关,您可能需要尝试)显然,您的连接字符串不正确,但很遗憾,您没有向我们显示用于连接SQL Server的连接字符串。
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