前一篇文章JDBC+MySQL实现保存图片到数据库,实现了图片的保存。这一篇文章对应的将图片从数据库中取回来。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 从MySQL数据库取回图片
*/
public class MySQL2Image {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8";
String username = "root";
String password = "12345678";
Connection con = DriverManager.getConnection(url,username,password);
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("select * from test01 where id=1");
byte[] img = null;
while (rs.next()) {
img = rs.getBytes(2);//通过图片在表中的列号得到
}
File file = new File("e:\\res.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(img);
fos.close();
rs.close();
statement.close();
con.close();
System.out.println("ok");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}