1. 程式人生 > >mysql blob 資料儲存和讀取

mysql blob 資料儲存和讀取

儲存前資料庫資訊


程式碼:

import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.io.*;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * blob測試
* create by frank
 * on 2018/02/08
 */
public class BlobTest {
    private static final String JDBC_URL 
= "jdbc:mysql://localhost:3306/wechatapp?useSSL=false"; private static final String USER = "root"; private static final String PWD = "******"; private static Connection connection = null; static { connection = getConn(); } public static Connection getConn() { Connection connection = null;
try { connection = (Connection) DriverManager.getConnection(JDBC_URL, USER, PWD); } catch (SQLException e) { e.printStackTrace(); } System.out.println("connected"); return connection; } public static int update() { int rst = 0; try
{ InputStream inputStream = new FileInputStream("E:\\demo.jpg"); String sql = "update ps_blob set img = ? where id = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setBlob(1, inputStream); preparedStatement.setInt(2, 2); rst = preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return rst; } public static void get() { String sql = "select id,img from ps_blob where id = ?"; InputStream inputStream = null; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 2); ResultSet rst = preparedStatement.executeQuery(); while (rst.next()) { System.out.println("id:" + rst.getInt(1)); Blob blob = rst.getBlob(2); inputStream = blob.getBinaryStream(); OutputStream outputStream =new FileOutputStream("E:\\demo1.jpg"); int x = 0; byte[] a = new byte[1024]; while ((x = inputStream.read(a)) != -1) outputStream.write(a); outputStream.close(); inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println( BlobTest.update()); BlobTest.get(); } }

執行完成後檢視 E:\\demo.jpg1


資料庫資料變化


只顯示(BLOB)代表插入二進位制流位 byte位元組數為0