Saving picture in database

Post your questions regarding programming in C# in here.
4 posts Page 1 of 1
Contributors
User avatar
hortencio
New Member
New Member
Posts: 19
Joined: Thu Apr 19, 2012 1:41 am

Saving picture in database
hortencio
Hello everyone

I´m building a program for registering students.So, i want put a picture of each student and then save in the database. I´m not using sql i just drag and drop the database from access to vb 2010. is there any code to do wha i´m asking? thanks.
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

Re: Saving picture in database
mandai
Which database type are you using?
User avatar
hortencio
New Member
New Member
Posts: 19
Joined: Thu Apr 19, 2012 1:41 am

Re: Saving picture in database
hortencio
This is the kind of data base im using:

Microsoft Office Access Database (.mdb)

sometimes i use this as well:

Microsoft Office Access 2007 Base de datos (.accdb)
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

Re: Saving picture in database
mandai
You can use this sample to insert/retrieve an image from an Access database:
Code: Select all
    Private Sub btnInsert_Click(sender As System.Object, e As System.EventArgs) Handles btnInsert.Click

        Dim connection As OleDbConnection = New OleDbConnection()
        connection.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source=test.mdb"

        connection.Open()

        Dim cmd As OleDbCommand = connection.CreateCommand()

        'create an example table
        cmd.CommandText = "CREATE TABLE test (images LONGBINARY)"
        cmd.ExecuteNonQuery()

        'insert the image
        Dim imageBytes As Byte() = File.ReadAllBytes("test.png")
        Dim param As OleDbParameter = cmd.Parameters.Add("@image", OleDbType.LongVarBinary, imageBytes.Length)
        param.Value = imageBytes
        cmd.CommandText = "INSERT INTO test VALUES (@image)"

        cmd.ExecuteNonQuery()

        'display the image (at record 0)
        cmd.CommandText = "SELECT images FROM test"
        Dim reader As OleDbDataReader = cmd.ExecuteReader()
        reader.Read()

        Dim size As Long = reader.GetBytes(0, 0, Nothing, 0, 0) 'specifying no buffer causes the size to be returned
        Dim buffer(size - 1) As Byte
        reader.GetBytes(0, 0, buffer, 0, buffer.Length)
        reader.Close()
        connection.Close()

        Dim ms As MemoryStream = New MemoryStream(buffer)
        Dim img As Image = Image.FromStream(ms)
        PictureBox1.Image = img

    End Sub
I understand accdb also supports similar sytntax.
4 posts Page 1 of 1
Return to “General coding help”