1. 程式人生 > 實用技巧 >【JDBC第4章】操作BLOB型別欄位

【JDBC第4章】操作BLOB型別欄位

第4章:操作BLOB型別欄位

4.1 MySQL BLOB型別

  • MySQL中,BLOB是一個二進位制大型物件,是一個可以儲存大量資料的容器,它能容納不同大小的資料。
  • 插入BLOB型別的資料必須使用PreparedStatement,因為BLOB型別的資料無法使用字串拼接寫的。

  • MySQL的四種BLOB型別(除了在儲存的最大資訊量上不同外,他們是等同的)

  • 實際使用中根據需要存入的資料大小定義不同的BLOB型別。
  • 需要注意的是:如果儲存的檔案過大,資料庫的效能會下降。
  • 如果在指定了相關的Blob型別以後,還報錯:xxx too large,那麼在mysql的安裝目錄下,找my.ini檔案加上如下的配置引數: max_allowed_packet=16M
    。同時注意:修改了my.ini檔案之後,需要重新啟動mysql服務。

4.2 向資料表中插入大資料型別

//獲取連線
Connection conn = JDBCUtils.getConnection();
        
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);

// 填充佔位符
ps.setString(1, "徐海強");
ps.setString(2, "[email protected]");
ps.setDate(3, new Date(new java.util.Date().getTime()));
// 操作Blob型別的變數
FileInputStream fis = new FileInputStream("xhq.png");
ps.setBlob(4, fis);
//執行
ps.execute();
        
fis.close();
JDBCUtils.closeResource(conn, ps);

4.3 修改資料表中的Blob型別欄位

Connection conn = JDBCUtils.getConnection();
String sql = "update customers set photo = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);

// 填充佔位符
// 操作Blob型別的變數
FileInputStream fis = new FileInputStream("coffee.png");
ps.setBlob(1, fis);
ps.setInt(2, 25);

ps.execute();

fis.close();
JDBCUtils.closeResource(conn, ps);

4.4 從資料表中讀取大資料型別

String sql = "SELECT id, name, email, birth, photo FROM customer WHERE id = ?";
conn = getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, 8);
rs = ps.executeQuery();
if(rs.next()){
    Integer id = rs.getInt(1);
    String name = rs.getString(2);
    String email = rs.getString(3);
    Date birth = rs.getDate(4);
    Customer cust = new Customer(id, name, email, birth);
    System.out.println(cust); 
    //讀取Blob型別的欄位
    Blob photo = rs.getBlob(5);
    InputStream is = photo.getBinaryStream();
    OutputStream os = new FileOutputStream("c.jpg");
    byte [] buffer = new byte[1024];
    int len = 0;
    while((len = is.read(buffer)) != -1){
        os.write(buffer, 0, len);
    }
    JDBCUtils.closeResource(conn, ps, rs);
        
    if(is != null){
        is.close();
    }
        
    if(os !=  null){
        os.close();
    }
    
}