Chèn Và đọc Hình Từ Cơ Sở Dữ Liệu

Thao tác với dữ liệu BLOBs với JDBC. Trong bài viết này, chúng ta cùng làm việc với trường hình ảnh(mở rộng ra là BLOBs – Binary Large Objects) với JDBC. Công việc của chúng ta sẽ là lưu hình từ 1 file vào cơ sở dữ liệu và đọc hình từ cơ sở dữ liệu ra lưu xuống 1 file. Với JDBC, những công việc trên thật dễ dàng và có nhiều cách. Đây là một. Cơ sở dữ liệu tôi sử dụng ở đây là my SQL. Bạn có thể dùng bằng MsSQL hay… Đầu tiên bạn tạo bạng MyPictures với cấu trúc Code: create table MyPictures ( id INT PRIMARY KEY, name VARCHAR(100), photo BLOB );

Bây giờ bạn có thể coding được rồi. Nhớ rằng project của bạn phải tham chiếu đến thư viện mysql jdbc driver nhé. Code 1: Chèn hình từ file vào cơ sở dữ liệu:

package vovanhai.wordpress.com; 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("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost/vvhimagedb"; Connection conn = DriverManager.getConnection(url, "root", ""); String sql="insert into MyPictures(id,name,photo) values (?,?,?)"; FileInputStream fis = null; PreparedStatement ps = null; try { conn.setAutoCommit(false); File file = new File("images/java.png"); fis = new FileInputStream(file); ps = conn.prepareStatement(sql); ps.setString(1, "001"); ps.setString(2, "java image"); ps.setBinaryStream(3, fis, (int) file.length()); ps.executeUpdate(); conn.commit(); } finally { ps.close(); fis.close(); } } }

Code 2: Lấy hình từ cơ sở dữ liệu rồi lưu vào file

package vovanhai.wordpress.com;

import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet;

public class ReadPictureFromMySQL { public static void main(String[] args) throws Exception{ Class.forName(“com.mysql.jdbc.Driver”); String url=”jdbc:mysql://localhost/vvhimagedb”; Connection conn = DriverManager.getConnection(url, “root”, “”); String sql=”select * from mypictures”; ResultSet rs=conn.createStatement().executeQuery(sql); if(rs.next()){ int id=rs.getInt(1); String name = rs.getString(2); File image = new File(“c:\\java.png”); FileOutputStream fos = new FileOutputStream(image);

byte[] buffer = new byte[1]; InputStream is = rs.getBinaryStream(3); while (is.read(buffer) > 0) { fos.write(buffer); } System.out.println(id+”; “+name); fos.close(); conn.close(); } } }

OK

Share this:

  • Facebook
  • X
Like Loading...

Từ khóa » Chèn ảnh Vào Mysql