Insert an Image in an Accesss Database

The following code asks for a path of a (Gif) image,and then inserts the Gif image to an Access database.



Imports System
Imports System.IO
Imports System.Data

Public Class SaveImage
Shared Sub main()

Dim o As System.IO.FileStream
Dim r As StreamReader
Dim gifFile As String

Console.Write("Enter a Valid .Gif file path")
gifFile = Console.ReadLine

If Dir(gifFile) = "" Then
Console.Write("Invalid File Path")
Exit Sub
End If

o = New FileStream(gifFile, FileMode.Open, FileAccess.Read, FileShare.Read)
r = New StreamReader(o)

Try

Dim FileByteArray(o.Length - 1) As Byte
o.Read(FileByteArray, 0, o.Length)
Dim Con As New _ System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data

Source=Test.mdb")

Dim Sql As String = "INSERT INTO Images (Pic,FileSize) VALUES (?,?)"
Dim Cmd As New System.Data.OleDb.OleDbCommand(Sql, Con)
Cmd.Parameters.Add("@Pic", System.Data.OleDb.OleDbType.Binary, o.Length).Value = FileByteArray
Cmd.Parameters.Add("@FileSize", System.Data.OleDb.OleDbType.VarChar, 100).Value = o.Length

Con.Open()
Cmd.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
Console.Write(ex.ToString)

End Try
End Sub
End Class

A file will be inserted in the Database each time the code is executed.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: