jdbc取出MySQL中的图片(blob)

 

 库名:shuyue  表名:img  

 

package 测试;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.ImageIcon;

public class T {

public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/shuyue","root","");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static ImageIcon getImg(int imgid){

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select img from img where id = ?";
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, imgid);
rs = ps.executeQuery();
rs.next();
Blob photo = rs.getBlob(1);
byte[] imageData =photo.getBytes(1,photo.getBinaryStream().available());
ImageIcon imageIcon = new ImageIcon(imageData);

return imageIcon;

} catch (Exception e) {
e.printStackTrace();
}
return null ;
}

//该方法已经返回ImageIcon对象了,可直接放入Swing使用


}

posted on 2019-12-31 11:37  有求必应  阅读(580)  评论(0)    收藏  举报

导航