使用Java Prepared语句无法使用setBinaryStream将二进制文件保存到PostgreSQL

时间:2019-04-01 08:59:37

标签: java postgresql binarystream

我有将二进制文件保存到PostgreSQL的代码,我正在使用JDK 1.5。但是我出错了。

在我打印插入语句后,然后在我的postgresql控制台中尝试,出现如下图所示的错误:

https://imgur.com/IF4hI3A

File file = new File("E:\\myimage.gif");
FileInputStream fis;

try {
    fis = new FileInputStream(file);
    PreparedStatement ps = conn.prepareStatement("INSERT INTO golf_fnb.coba VALUES (?)");
    ps.setBinaryStream(1, fis, (int)file.length());
    System.out.println("SQl: "+ps);
    ps.executeUpdate();
    ps.close();
    fis.close();
} catch (FileNotFoundException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

这是我的Eclipse控制台中的错误:

org.postgresql.util.PSQLException: ERROR: syntax error at or near "\"

    at org.postgresql.util.PSQLException.parseServerError(PSQLException.java:139)
    at org.postgresql.core.QueryExecutor.executeV3(QueryExecutor.java:152)
    at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:100)
    at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:43)
    at org.postgresql.jdbc1.AbstractJdbc1Statement.execute(AbstractJdbc1Statement.java:517)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:50)
    at org.postgresql.jdbc1.AbstractJdbc1Statement.executeUpdate(AbstractJdbc1Statement.java:273)
    at finger.ConsoleUserInterfaceFactory$ConsoleUserInterface.verify4(ConsoleUserInterfaceFactory.java:605)
    at finger.ConsoleUserInterfaceFactory$ConsoleUserInterface.run(ConsoleUserInterfaceFactory.java:117)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:651)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:676)
    at java.lang.Thread.run(Thread.java:595)

1 个答案:

答案 0 :(得分:0)

我认为主要错误是在使用列。语法:INSERT INTO TABLE(col1, ...) VALUES(val1, ...)

也可能是您(or someone having a similar problem) intended更新golf_fnb SET coba =吗? id =?`。对于INSERT:

try (FileInputStream fis = new FileInputStream(file);
        PreparedStatement ps = conn.prepareStatement("INSERT INTO golf_fnb(coba) VALUES (?)",
                Statement.RETURN_GENERATED_KEYS)) {
    ps.setBinaryStream(1, fis, (int)file.length());
    System.out.println("SQl: "+ps);
    int updateCount = ps.executeUpdate();
    if (updateCount == 1) {
        try (ResultSet rs = ps.getGeneratedKeys()) {
            if (rs.next()) {
                long id = rs.getLong(1);
                System.out.println("ID " + id);
                return;
            }
        }
     }
} catch (SQLException | IOException e) {
    e.printStackTrace();
}
  • 使用try-with-resources自动关闭所有资源。
  • 插入的记录可能要查找。假设主键较长,则添加getGeneratedKeys。
  • \',撇号可能会带来一些问题。也许应该手动为\047。我希望驱动程序进行的这种八进制转换会随着上面的新语法而消失。