PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

File kosong setelah diunduh

Peter, ini bekerja untuk saya dengan PostgreSQL 9.3 dan Java OpenJDK 7.

Menulis dengan LargeObjectAPI:

public static void main(String[] args) throws SQLException, FileNotFoundException, IOException {
    Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test01", "postgres", "postgres");
    conn.setAutoCommit(false);
    File file = new File("/home/user/Pictures/somePicture.jpg");
    FileInputStream fis = new FileInputStream(file);
    LargeObjectManager lom = PGConnection.class.cast(conn).getLargeObjectAPI();
    long oid = lom.createLO(LargeObjectManager.READ | LargeObjectManager.WRITE);
    LargeObject lob = lom.open(oid, LargeObjectManager.WRITE);
    byte[] buffer = new byte[2048];
    int s = 0;
    while ((s = fis.read(buffer, 0, buffer.length)) > 0) {
        lob.write(buffer, 0, s);
    }
    lob.close();
    fis.close();

    PreparedStatement ps = conn.prepareStatement("insert into test(id, name, content) values (nextval('test_id_seq'), ?, ?)");
    ps.setString(1, "foto01");
    ps.setLong(2, oid);
    ps.executeUpdate();
    ps.close();
    conn.commit();
}

Membaca objek besar dari database:

public static void main(String[] args) throws SQLException, FileNotFoundException, IOException {
        Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test01", "postgres", "postgres");
        conn.setAutoCommit(false);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select id, name, content from test");

        LargeObjectManager lom = PGConnection.class.cast(conn).getLargeObjectAPI();
        byte[] buffer = new byte[2048];
        int s = 0;
        while(rs.next()) {
            File file = new File("/tmp", rs.getLong("id") + "_" + rs.getString("name"));
            FileOutputStream fos = new FileOutputStream(file);
            LargeObject lob = lom.open(rs.getLong("content"), LargeObjectManager.READ);
            while((s = lob.read(buffer, 0, buffer.length)) > 0) {
                fos.write(buffer, 0, buffer.length);
            }
            lob.close();
            fos.close();
        }

        conn.close();
    }

Tabel uji didefinisikan sebagai

create table test (id serial, name varchar(256), content oid);



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Paket 'pgadmin4' tidak memiliki kandidat instalasi, untuk Ubuntu 20.04

  2. Pengelompokan berdasarkan tanggal, dengan 0 saat count() tidak menghasilkan garis

  3. Pasangan nilai kunci di PostgreSQL

  4. kebuntuan postgresql

  5. Cara menggunakan kursor sisi server dengan psycopg2