参照了wzuomin回答问题的回复,谢谢。
Public Function SaveImgToSQLSERVER(ByVal TableName As String, ByVal FieldName As String, ByVal ImgFileName As String, ByVal id As String) As Integer
Dim strSql As String = "update " & TableName & " set " & FieldName & " = @img " & " where id=" & Chr(39) & id & Chr(39)
Dim rowsAffected As Integer = 0
Dim cn As New SqlConnection("Server=" & g_DatabaseServerIp & ";Initial Catalog=" & g_DatabaseName & ";UID=" & g_DatabaseUser & ";Pwd=" & g_DatabaseUserPassword)
cn.Open()
Dim Cmd As New SqlCommand()
Cmd.Connection = cn
Cmd.CommandText = strSql
Dim fs As New IO.FileStream(ImgFileName, IO.FileMode.Open, IO.FileAccess.Read)
Dim bytes(fs.Length) As Byte
fs.Read(bytes, 0, fs.Length)
fs.Close() : fs = Nothing
Cmd.Parameters.Add("@img", SqlDbType.Image).Value = bytes
rowsAffected = Cmd.ExecuteNonQuery()
Cmd.Dispose()
cn.Close()
cn.Dispose()
Return rowsAffected
End Function
调用例子
SaveImgToSQLSERVER("tbMergeIns", "imgTotalWeight1", Application.StartupPath & "\carphoto.jpg", "201906140001")
Public Function GetImgFromSQLSERVER(ByVal TableName As String, ByVal FileldName As String, ByVal ImgFileName As String, ByVal id As String) As Image
Dim strSql As String = "select top 1 " & FileldName & " from " & TableName & " where id=" & id
Dim cn As New SqlConnection("Server=" & g_DatabaseServerIp & ";Initial Catalog=" & g_DatabaseName & ";UID=" & g_DatabaseUser & ";Pwd=" & g_DatabaseUserPassword)
cn.Open()
Dim img As Image = Nothing
Dim Cmd As New SqlCommand()
Cmd.Connection = cn
Cmd.CommandText = strSql
Dim bytes() As Byte = IIf(IsDBNull(Cmd.ExecuteScalar), Nothing, Cmd.ExecuteScalar)
If bytes IsNot Nothing Then
If bytes.Length > 0 Then
Dim fs As New IO.FileStream(ImgFileName, IO.FileMode.Create, IO.FileAccess.Write)
fs.Write(bytes, 0, bytes.Length)
fs.Close() : fs = Nothing
End If
End If
Cmd.Dispose()
cn.Close()
cn.Dispose()
Return img
End Function
调用例子
GetImgFromSQLSERVER("tbMergeIns", "imgTotalWeight1", Application.StartupPath & "\zx.jpg", "201906140001")