执行SQL语句

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

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

    3. 关闭语句对象。

      1. stmt.close();

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

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

      1. PreparedStatement pstmt = con.prepareStatement("UPDATE customer_t1 SET c_customer_name = ? WHERE c_customer_sk = 1");
    2. 调用PreparedStatement的setShort设置参数。

      1. pstmt.setShort(1, (short)2);
    3. 调用PreparedStatement的executeUpdate方法执行预编译SQL语句。

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

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

        1. Connection myConn = DriverManager.getConnection("url","user","password");
      2. 调用CallableStatement的setInt方法设置参数。

        1. cstmt.setInt(2, 50);
        2. cstmt.setInt(1, 20);
        3. cstmt.setInt(3, 90);
      3. 调用CallableStatement的registerOutParameter方法注册输出参数。

        1. cstmt.registerOutParameter(4, Types.INTEGER); //注册out类型的参数,类型为整型。
      4. 调用CallableStatement的execute执行方法调用。

        1. cstmt.execute();
      5. 调用CallableStatement的getInt方法获取输出参数。

        示例:

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

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

        1. Connection conn = DriverManager.getConnection("url","user","password");
        2. PreparedStatement pstmt = conn.prepareStatement("INSERT INTO customer_t1 VALUES (?)");
      2. 针对每条数据都要调用setShort设置参数,以及调用addBatch确认该条设置完毕。

        1. pstmt.setShort(1, (short)2);
        2. pstmt.addBatch();
      3. 调用PreparedStatement的executeBatch方法执行批处理。