java - JDBC异常处理: warning suppression

标签 java jdbc

我目前正在学习一些基本的 java SQL 编码,为我的 SQL 项目制作基本的终端 UI。我一直在使用 PostgreSQL

我正在使用PreparedStatement为了确保自己免受 SQL 注入(inject),安全总比后悔好。 PreparedStatement似乎总是出于某种原因发出警告,我认为这是异常的子类(并且应该被捕获在异常中)。

在我的 SQL 触发器和函数中,我创建并测试了应该引发异常的情况,并且它们都得到并正常工作 catch block 。

我想使用@Supresswarnings让编译器知道我想抑制警告,但我可能想在 catch block 中捕获一些警告,因此我可能正在寻找不同的解决方案。

问题/问题是:

  1. 我希望将我的打印放在 try block 中,即没有异常被触发。
  2. 执行 preparedStmt.executeQuery 后可以做什么来获得我的打印结果在 try block 中?
  3. 正在使用@SuppressWarnings在处理这样的异常处理时通常被认为是良好的编码实践?
  4. 如果我的说法有误 preparedStatement.executeQuery()总是发出警告,什么是 SQL 语言中的警告?

我的代码:

void registerStudent(Connection conn, String toBeInserted, String insertedTo)
throws SQLException{
    ResultSet res;
    String query = "INSERT INTO Registrations VALUES (?, ?)";

    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1, toBeInserted);
    ps.setString(2, insertedTo);

    try {
        ps.executeQuery();                        

    }catch (SQLException e) {

        SQLWarning warning = ps.getWarnings();
        if (warning != null){

        System.out.println("Yay,  insert succeeded!
    values: "+ toBeInserted +" were inserted into 
    "+insertedTo);

        }else {
            System.out.println("Nothing inserted, here goes the big exception SQL fired for ya'll: " 
         + e.getMessage());
        }
    }
  }

最佳答案

还有一些缺陷。我还添加了自动增量主键的情况 - 您可以在插入后检索它。

缺陷:

  • 列出您插入的字段,这样以后在数据库中添加列就不会出现问题,并且代码中列的顺序也很清晰。
  • 使用 try-with-resources 来关闭语句、结果集等,即使其中返回内部或引发异常。
  • 使用executeUpdate 进行INSERT(以及类似的修改操作),返回更新计数。
  • 您捕获了 SQLException,然后应该重新抛出该异常,以便让调用者确定在严重失败时要执行的操作。
  • SQLWarnings(实际的 SQL 和 SQLException 也是如此)可能很有趣, 虽然我不经常看到 SQLWarnings 被处理。也许对于这种简单的情况忘记它,而是首先在单独的 SQL 工具中尝试新的 SQL 语句。

所以:

/**
 * @return the generated primary key, the Student ID.
 */
int registerStudent(Connection conn, String toBeInserted, String insertedTo)
        throws SQLException {
    String query = "INSERT INTO Registrations(ToBeInserted, InsertedInto) VALUES(?, ?)";

    try (PreparedStatement ps = conn.prepareStatement(query),
            Statement.RETURN_GENERATED_KEYS) {
        ps.setString(1, toBeInserted);
        ps.setString(2, insertedTo);
        int updateCount = ps.executeUpdate();                        
        if (updateCount == 1) {
            try (ResultSet rs = ps.getGeneratedKeys()) {
                if (rs.next()) {
                    int id = rs.getInt(1);
                    return id;
                }
            }
            throw new SQLException("No primary key generated");
        } else {
            SQLWarning warning = ps.getWarnings();
            Logger.getLogger(Xyz.class.getName()).info("Not added, values: "
                + toBeInserted + " were not inserted into "+ insertedTo + ": " + warning);
            throw new SQLException("Not added");
        }
    }
}

关于java - JDBC异常处理: warning suppression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47812018/

相关文章:

java - hibernate :无法从 ResultSet 和 IllegalArgumentException:GregorianCalendar.computeTime 读取实体状态

java - 在 JSP 中动态建立 Oracle DB 连接

java - 想要向我的代码添加验证,如果表不存在,则应该在 java 中创建新表

java - JDBC 异常 : Operation not allowed after ResultSet closed

java - 如何从Java程序调用Oracle函数

java - Gradle JavaExec 任务,如何使用 allJvmArgs 属性

java - 从其 BlobKey 获取 Google Cloud Storage 文件

java - hibernate 和锁定

java - 检索表时无法获取表中 0 位置的第一个元素?

java - 在Eclipse中,是否可以默认设置注释处理和工厂路径?