学习记录:VB.NET向SQL SERVER数据库中某个字段写入JPG文件,以及从SQL SERVER数据库中某个字段读出数据写成JPG文件

参照了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")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iamtsfw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值