gpt4 book ai didi

java - 使用 Java 将图像上传到 PostgreSQL

转载 作者:行者123 更新时间:2023-12-01 14:02:40 24 4
gpt4 key购买 nike

我正在尝试编写一个 JSP Web 应用程序,允许将图像上传到 PostgreSQL 数据库。我正在关注this作为指导,但图像未上传到数据库,方法(如下)进入捕获。

这是我到目前为止的代码:

public boolean upIm() {
try {
File file = new File("bg.jpg");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = con.prepareStatement("INSERT INTO images VALUES (?, ?)");
ps.setString(1, "background");
ps.setBinaryStream(2, fis, (int) file.length());
ps.executeUpdate();
ps.close();
fis.close();

return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

FileInputStream 似乎有问题,因为转到数据库的语句是 INSERT INTO images VALUES ('background', ?) ,并且我已经测试了 file.length( )并且工作正常。

就是这样;如果您需要更多信息或更多代码,请告诉我。

编辑:我得到这个堆栈跟踪:

org.postgresql.util.PSQLException: ERROR: relation "images" does not exist
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1886)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:555)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:363)
at bd.provaImg.upIm(provaImg.java:50)
at bd.prova2.main(prova2.java:14)

我认为位置 13 是类中的行(此处未显示),它只是实例化包含此方法的类。

最佳答案

这是你的错误。在黑板上写下1000遍我不会再这样做了!

// BAD BAD BAD BAD BAD BAD BAD
} catch (Exception e) {
return false;
}

这会更近一步,但仍然不好:

// BAD BAD BAD BAD BAD BAD BAD
} catch (Exception e) {
//NEVER do this. It hides the stacktrace, the main point of logging an error...
System.err.println(e.getMessage());
return false;
}

正确:

} catch (Exception e) {
e.printStackTrace();
return false;
}

或者更好的是,使用适当的记录器:

} catch (Exception e) {
//notice the ",e"! 99.999999% you have to log with full stacktrace!
LOG.error("Unexpected error during file upload", e);
return false;
}

你接受了这个错误。这不好。非常非常糟糕。此类代码可能会成为解雇的理由...

现在:

  • 请发布您获得的完整堆栈跟踪
  • 标记错误所在行

关于java - 使用 Java 将图像上传到 PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19224004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com