package jdbc;import java.io.*;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class Demo04 {private InputStream is;private FileOutputStream fos;// 保存长二进制(LONGBLOB)数据类型public void saveImage() {String sql = "insert into test(img) values(?)";try (// 1. 获取数据库连接Connection conn = JDBCUtils.getConnection();// 2. 预编译 SQL 语句PreparedStatement pstmt = conn.prepareStatement(sql);// 3. 传入参数// 3.1 获取图片输入流InputStream is = Demo04.class.getClassLoader().getResourceAsStream("Tree.jpg");) {// 3.2 传参pstmt.setBinaryStream(1, is);// 4. 执行 SQL 语句pstmt.executeUpdate();} catch (IOException | SQLException e) {e.printStackTrace();}}// 读取长二进制(LONGBLOB)数据类型public void getAsImage() throws IOException {String sql = "select * from test where id = 1;";try (// 1. 获取数据库连接Connection conn = JDBCUtils.getConnection();// 2. 预编译 SQL 语句PreparedStatement pstmt = conn.prepareStatement(sql);// 3. 执行 SQL 语句ResultSet rs = pstmt.executeQuery();) {// 4. 从结果集对象中读取数据if (rs.next()) {// 4.1 获取图片输入流is = rs.getBinaryStream("img");// 4.2 创建图片输出流fos = new FileOutputStream(new File("tree.jpg"));// 4.3 实际读取到的数据长度int len = 0;// 4.3 使用byte[]数组来盛装数据byte[] bytes = new byte[1024];while((len = is.read(bytes)) != -1) {fos.write(bytes, 0, len);}}} catch (SQLException | IOException e) {e.printStackTrace();} finally {if (is != null) {is.close();}if (fos != null) {fos.close();}}}public static void main(String[] args) throws IOException {Demo04 demo04 = new Demo04();demo04.saveImage();demo04.getAsImage();}}
1200字范文,内容丰富有趣,写作的好帮手!