sqlite从数据库中读取pdf文件

时间:2017-11-07 16:20:33

标签: vb.net sqlite pdf

我有点被困在这...... 我有一个代码将PDF文件作为字节插入blob:

Dim ofd As New OpenFileDialog
With ofd
    .InitialDirectory = Application.StartupPath
    .Filter = "PDF Files|*.pdf"
    .FileName = Nothing
    .ShowDialog()
End With
MsgBox(ofd.FileName)

Dim filePath As String = ofd.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))

br.Close()
fs.Close()

Dim con As New SQLiteConnection(db)
Dim cmd As New SQLiteCommand
Try
    con.Open()
    cmd = con.CreateCommand
    cmd.CommandText = "UPDATE Employee SET File = @File WHERE ID = 20"
    cmd.Parameters.Add("@File", SqlDbType.Binary).Value = bytes
    cmd.ExecuteNonQuery()
Catch ex As Exception
    MsgBox(ex.Message)
Finally
    con.Close()
    cmd.Dispose()
End Try

这有效,但现在我需要将其反转并加载PDF文件(我不想将PDF保存回计算机,我只需要查看它...) 这是我必须检索PDF文件:

Dim con As New SQLiteConnection(db)
Dim cmd As New SQLiteCommand
Dim File As New DataTable

Try
    con.Open()
    cmd = con.CreateCommand
    Dim CommandText As String = "SELECT File FROM Employee WHERE ID = 20"
    Dim adapter As New SQLiteDataAdapter(CommandText, con)
    adapter.Fill(File)

Catch ex As Exception
    MsgBox(ex.Message)
Finally
    con.Close()
    cmd.Dispose()
End Try

但它不起作用......

任何人都有其他办法吗?

1 个答案:

答案 0 :(得分:0)

所以这就是我修复它的方法......

    Try
        con.Open()
        cmd = con.CreateCommand
        cmd.CommandText = "SELECT File FROM Employee WHERE ID = 20"
        Dim bytes As Byte() = cmd.ExecuteScalar()
        Dim fs As FileStream = New FileStream("d:\test.pdf", FileMode.Create)
        fs.Write(bytes, 0, bytes.Length)
        fs.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        con.Close()
        cmd.Dispose()

    End Try

感谢您的帮助