Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store a picture in MySQL?

I want to store an image in a MySQL database. I have created a table with a BLOB datatype, but now how do I store the image in this table?

like image 702
Karthik.m Avatar asked Dec 21 '09 09:12

Karthik.m


People also ask

Can you store a picture in SQL?

The IMAGE data type in SQL Server has been used to store the image files. Recently, Microsoft began suggesting using VARBINARY(MAX) instead of IMAGE for storing a large amount of data in a single column since IMAGE will be retired in a future version of MS SQL Server.

Can you store a picture in a database?

A database gives you the opportunity to store photos and other small images in a database table. You can create such a database table for example when you want to create an online photo album with descriptions of your photos. Storing images in a database table is not recommended.

Where are images stored in MySQL?

MySQL databases are sequentially stored on a disk. This means that your database picture files are converted to blobs, embedded into a database, and then kept on a disk.

What is the datatype for image in MySQL?

In MySQL, the preferred data type for image storage is BLOB.


2 Answers

You may want to check out the following example:

From java2s.com: Insert picture to MySQL:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertPictureToMySql {
  public static void main(String[] args) throws Exception, IOException, SQLException {
    Class.forName("org.gjt.mm.mysql.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
    String INSERT_PICTURE = "INSERT INTO MyPictures (photo) VALUES (?)";

    FileInputStream fis = null;
    PreparedStatement ps = null;
    try {
      conn.setAutoCommit(false);
      File file = new File("/tmp/photo.png");
      fis = new FileInputStream(file);
      ps = conn.prepareStatement(INSERT_PICTURE);
      ps.setBinaryStream(1, fis, (int) file.length());
      ps.executeUpdate();
      conn.commit();
    } finally {
      ps.close();
      fis.close();
    }
  }
}

MySQL Table:

CREATE TABLE MyPictures (
   photo  BLOB
);

If the image is located on your MySQL server host, you could use the LOAD_FILE() command from a MySQL client:

INSERT INTO MyPictures (photo) VALUES(LOAD_FILE('/tmp/photo.png'));
like image 148
Daniel Vassallo Avatar answered Sep 27 '22 18:09

Daniel Vassallo


read the content of the file (BINARY) and insert it in insert \ update MYSQL query

a lot of example in google :

http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm

http://www.roseindia.net/jdbc/save_image.shtml

http://www.jguru.com/faq/view.jsp?EID=1278882

like image 40
Haim Evgi Avatar answered Sep 27 '22 18:09

Haim Evgi