Pages

Wednesday, October 22, 2008

Insert Picture to MySQL With Java

Tipe data blob menyediakan space untuk penyimpanan gambar, text dan file yang ukurannnya besar. Berikut ini cara menyimpan gambar ke dalam type data blob di MySQL dengan menggunakan Java.


/*
Defining the Table: Oracle and MySql

create table MyPictures (
id INT PRIMARY KEY,
name VARCHAR(0),
photo BLOB
);
*/
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/a71b", "root", "");
String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";

FileInputStream fis = null;
PreparedStatement ps = null;
try {
conn.setAutoCommit(false);
File file = new File("mgr.jpg");
fis = new FileInputStream(file);
ps = conn.prepareStatement(INSERT_PICTURE);
ps.setString(1, "001");
ps.setString(2, "Mgr");
ps.setBinaryStream(3, fis, (int) file.length());
ps.executeUpdate();
conn.commit();
} finally {
ps.close();
fis.close();
}
}
}

Silahkan mencoba dan semoga bermanfaat.

2 comments:

  1. lha nampilinya gmn pak??
    kok cuma nyimpen doank??

    ReplyDelete
  2. itu yang typedata nya BLOB kan pak??

    ReplyDelete

Popular Posts

Blog Archive

 

Iklan

Daily Calendar