JavaSE-向数据库保存图片并且读取
SqlDemo.java
package com.xieth.sql;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SqlDemo {
private Connection conn = null;
private PreparedStatement ps = null;
public SqlDemo() throws ClassNotFoundException, SQLException {
String driverClass = "com.mysql.jdbc.Driver";
String jdbcUrl = "jdbc:mysql:///person";// localhost可以省略
String user = "root";
String password = "12345";
Class.forName(driverClass); // 注册加载驱动
conn = DriverManager.getConnection(jdbcUrl, user, password);
System.out.println(conn); // 获取数据库连接
}
private void insertData() throws SQLException {
String path = "image/Head.jpg";
FileInputStream input = null;
byte[] buffer = null;
// 定义缓冲区
try {
input = new FileInputStream(new File(path));
// 构建文件输入流对象
buffer = new byte[input.available()];
// 构建缓冲区
input.read(buffer);
// 将图标读入缓冲区
} catch (Exception e) {
} finally {
if (input != null) {
try {
input.close(); // 关闭文件输入流
} catch (Exception e) {
e.printStackTrace();
}
}
}
String sql = "insert into user(img)" + "values(?)";
ps = conn.prepareStatement(sql);
ps.setBytes(1, buffer);
int count = ps.executeUpdate();
if (count > 0)
System.out.println("成功");
else
System.out.println("失败");
}
private byte[] getImage() throws SQLException{
byte[] buffer = null;
String sql = "select img from user";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
buffer = rs.getBytes("img");
return buffer;
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
SqlDemo s = new SqlDemo();
byte[] b = s.getImage();
new MainImage(b);
}
}
MainImage.java
package com.xieth.sql;
import java.awt.*;
import javax.swing.*;
public class MainImage extends JFrame {
private JLabel label = null;
private JPanel panel = null;
private byte[] buffer = null;
public MainImage(byte[] buffer) {
super("Image");
this.buffer = buffer;
panel = new JPanel();
init();
}
private void init() {
this.setSize(540, 390); // 设置长度和宽度
this.setLayout(null); // 自定义布局
this.setLocationRelativeTo(this.getOwner()); // 设置窗体的相对位置
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setSize(540, 400);
label = new JLabel(new ImageIcon(buffer));
panel.add(label);
add(panel);
this.setVisible(true);
}
}
数据库里面的数据:
运行效果:
成功读取数据库里面的图片