Wednesday, March 5, 2008

How to Insert An image into Access Database


The following code asks for a path of a Gif image. Then inserts the Gif image to an Access database.

 
File name is Image.vb
 
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.


No comments :

Post a Comment