JDBC 入门 - 操作SQL语句

时间:2015-01-25 12:25:57   收藏:0   阅读:259

操作 SQL 语句

Statement, PreparedStatement, CallableStatement

一旦建立好连接, 就可以与数据库交互. JDBC 中StatementPreparedStatement 和 CallableStatement 提供了SQL操作的相关API. 其中 CallableStatement 继承自 PreparedStatement, 而 PreparedStatement 又继承自 Statement. 他们的区别是:

尽管接口功能有不同, 但是使用方式大体相同, 分以下几步:

  1. 创建 Statement
  2. 执行 SQL 语句
  3. 关闭 Statement

在执行 SQL 语句的时候, 常用以下几个方法:

以下三个例子分别示例了如何适用他们.

SQL 的批处理操作

SQL 批处理能够允许添加多个 SQL 到 一个Statement对象, 并一并提交执行结果. 这减少了与 SQL 通信的频率. 但是, SQL 批处理不是 JDBC 要求一定要支持的. 使用前应该用 DatabaseMetaData.supportsBatchUpdates() 检查支持情况.

SQL 批处理相关的 API 有:

以下示例如何使用批处理往数据库添加数据:

 public static void batchInsertPosts(ArrayList<Post> posts) throws SQLException {
        Connection conn = getConnectionFromDS(dbProps);
        DatabaseMetaData md = conn.getMetaData();
        System.out.println("If support batch updates: " + md.supportsBatchUpdates());
        String sql = "INSERT INTO POSTS\n"
                   + "VALUES(NULL, ?, ?, DEFAULT, ?)";
        PreparedStatement stmt = conn.prepareCall(sql);

        for (Post post : posts) {
            stmt.setString(1, post.getTitle());
            stmt.setString(2, post.getContent());
            stmt.setBoolean(3, post.isVisible());
            stmt.addBatch();
        }
        stmt.executeBatch();
        printWarnings(stmt.getWarnings()); // 打印所有 warning. 见 "SQL异常处理"
        stmt.close();
        conn.close();
    }

 

SQL 异常处理

JDBC 中最常用的异常就是 SQLException, 不管是在建立连接, 还是在执行 SQL 语句的时候, 都有可能抛出这个异常. SQLException 包含以下信息:

以下代码示例如何打印异常链中的每个SQLException异常, 并且打印每个异常的 cause 链.

    public static void printSQLException(SQLException ex) {
        for (Throwable e : ex) {    // Iterator 会调用 getNextException()
            if (e instanceof SQLException) {

                e.printStackTrace(System.err);
                System.err.println("SQLState: " +
                        ((SQLException)e).getSQLState());

                System.err.println("Error Code: " +
                        ((SQLException)e).getErrorCode());

                System.err.println("Message: " + e.getMessage());

                Throwable t = ex.getCause();
                while(t != null) {  // 打印每个 cause
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }

 

除了发生致命错误产生抛出 SQLException 之外, ConnectionStatementResultSet 都有一个 getWarnings() 方法, 它返回一个 SQLWarningSQLWarning 继承自 SQLException, 可以向遍历 SQLException 一样遍历它:

    public static void printWarnings(SQLWarning warning)
        throws SQLException {
        while (warning != null) {
            System.out.println("Message: " + warning.getMessage());
            System.out.println("SQLState: " + warning.getSQLState());
            System.out.print("Vendor error code: ");
            System.out.println(warning.getErrorCode());
            System.out.println("");
            warning = warning.getNextWarning();
        }
    }

 

原文:http://www.cnblogs.com/pragmatic/p/4247998.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!