0

我有将二进制文件保存到 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)
4

1 回答 1

0

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

也可能是你(or someone having a similar problem) intendedUPDATE golf_fnb SET coba = ?WHERE id = ?`。对于插入:

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而不是也许。我希望驱动程序的这种到八进制的转换会随着上面的新语法消失。
于 2019-04-01T11:17:03.687 回答