更新时间:2025-07-08 GMT+08:00
分享

执行SQL语句

执行普通SQL语句

应用程序通过执行SQL语句来操作数据库的数据(不用传递参数的语句),需要按以下步骤执行:

  1. 调用Connection的createStatement方法创建语句对象。

    1
    Statement stmt = con.createStatement();
    

  2. 调用Statement的executeUpdate方法执行SQL语句。

    stmt.executeUpdate("create table if not exists test_01(" +
        "p_partkey int4," +
        "p_name text," +
        "P_MFGR char(25)," +
        "P_BRAND char(25)," +
        "p_type text," +
        "p_size int4," +
        "P_CONTAINER char(10)," +
        "p_retailprice decimal(15,2)," +
        "p_comment text)" +
        "store as orc;");

  3. 关闭语句对象。

    1
    stmt.close();
    

执行预编译SQL语句

预编译语句是只编译和优化一次,然后可以通过设置不同的参数值多次使用。由于已经预先编译好,后续使用会减少执行时间。因此,如果多次执行一条语句,请选择使用预编译语句。可以按以下步骤执行:

  1. 调用Connection的prepareStatement方法创建预编译语句对象。

    1
    PreparedStatement pstmt = con.prepareStatement("select * from test_01 where p_partkey = ?");
    

  2. 调用PreparedStatement的setShort设置参数。

    1
    pstmt.setString(1, "1502");
    

  3. 调用PreparedStatement的executeUpdate方法执行预编译SQL语句。

    1
    ResultSet resultSet = pstmt.executeQuery();
    

  4. 调用PreparedStatement的close方法关闭预编译语句对象。

    1
    pstmt.close();
    

执行批处理

用一条预处理语句处理多条相似的数据,数据库只创建一次执行计划,节省了语句的编译和优化时间。可以按如下步骤执行:

  1. 调用Connection的prepareStatement方法创建预编译语句对象。

    1
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO test_01 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);");
    

  2. 针对每条数据都要调用setShort设置参数,以及调用addBatch确认该条设置完毕。

    preparedStatement.setInt(1, 1);
    preparedStatement.setString(2, "name");
    preparedStatement.setString(3, "cata");
    preparedStatement.setString(4, "test4");
    preparedStatement.setString(5, "test5");
    preparedStatement.setInt(6, 2);
    preparedStatement.setString(7, "test7");
    preparedStatement.setBigDecimal(8, new BigDecimal(502.1));
    preparedStatement.setString(9, "test9");
    preparedStatement.addBatch();

  3. 调用PreparedStatement的executeBatch方法执行批处理。

    1
    int[] rowcount = pstmt.executeBatch();
    

  4. 调用PreparedStatement的close方法关闭预编译语句对象。

    1
    pstmt.close();
    

相关文档