大數據

java jdbc 操作 blob 類型的數據

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服務。

2 向數據表中插入大數據類型

//獲取連接
Connection conn = JDBCUtils.getConnection();
        
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
//java  fhadmin.org
// 填充佔位符
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);

3 修改數據表中的Blob類型字段

Connection conn = JDBCUtils.getConnection();
String sql = "update customers set photo = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
//java fhadmin.org
// 填充佔位符
// 操作Blob類型的變量
FileInputStream fis = new FileInputStream("coffee.png");
ps.setBlob(1, fis);
ps.setInt(2, 25);
ps.execute();
fis.close();
JDBCUtils.closeResource(conn, ps);

4 從數據表中讀取大數據類型

//java fhadmin.org
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();
    }
    
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *