Skip to content

适用虚谷数据库版本

v12.9



适用虚谷数据库版本

v12.9


示例

📄字数 3.4K
👁️阅读量 加载中...

Statement 示例

  • Statement 常见使用方式

示例1:

java
public static void main(String[] args) throws SQLException {
    //创建一个数据库连接对象
    Connection conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM","SYSDBA","SYSDBA");

    //创建一个Statement对象
    Statement stmt = conn.createStatement();
    //使用Statement对象创建一张表
    stmt.execute("create table tb_stu(id int identity (1,1) not null primary key,name varchar(10));");
    //向表插入一条数据
    stmt.execute("insert into tb_stu(name) values('zs');");
    //更改表中数据
    stmt.executeUpdate("update tb_stu set name='ls' where id=1;");
    //查看表中数据,将结果存入Result对象中
    ResultSet rs = stmt.executeQuery("select name from tb_stu where id=1;");
    while (rs.next()){
        System.out.println(rs.getString(1));
    }
    
    //关闭对象释放资源
    rs.close();
    stmt.close();
    conn.close();
}
  • Statement 进行批量数据操作

注意

  • 执行批处理操作前,自动提交模式设置为FALSE
  • 执行批处理操作,并进行手动提交(commit)
  • 执行批处理操作后,自动提交模式恢复为 TRUE
  • 执行批处理操作异常发生时,进行 rollback(回滚)

示例2: 通过 Statement 批量操作数据

java
public static void main(String[] args) throws SQLException, ClassNotFoundException {
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM", "SYSDBA", "SYSDBA");
        //创建Statement对象
        stmt = conn.createStatement();
        //设置事务非自动提交
        conn.setAutoCommit(false);
        // 添加多条SQL语句到批处理中
        stmt.addBatch("insert into tb_stu(name) values('zs');");
        stmt.addBatch("insert into tb_stu(name) values('ls');");
        stmt.addBatch("insert into tb_stu(name) values('zl');");
        //执行批处理操作
        stmt.executeBatch();
        System.out.println("插入成功!");
        //执行成功后进行数据提交
        conn.commit();
        System.out.println("提交成功!");
        //关闭非自动提交
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        if (!conn.isClosed()) {
            //出现异常,回滚事务
            conn.rollback(); 
            System.out.println("提交失败,回滚!");
            //关闭非自动提交
            conn.setAutoCommit(true); 
        }
    } finally {
        if (stmt != null) {
            //关闭操作对象
            stmt.close();
        }
    }
}

PreparedStatement 示例

  • PreparedStatement 常见使用方法

示例1:

java
public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM","SYSDBA","SYSDBA");

    //创建PreparedStatement对象,其中 ? 表示参数
    PreparedStatement pstm = conn.prepareStatement("insert into tb_stu(name) values(?);");
    //使用setXxx()方法给参数传值
    pstm.setString(1,"zs");
    //执行SQL语句
    pstm.execute();

    //关闭对象释放资源
    pstm.close();
    conn.close();
}
  • 通过PreparedStatement进行批量数据操作

注意

  • 执行批处理操作前,自动提交模式设置为FALSE
  • 执行批处理操作,并进行手动提交(commit),数据量大时,设置手动提交间隔
  • 执行批处理操作后,自动提交模式恢复为 TRUE
  • 执行批处理操作异常发生时,进行rollback(回滚)
  • PreparedStatement执行语句不能为DDL语句

示例2: 将 10000 条记录插入数据库中,每 100 条执行一次提交操作

java
public static void main(String[] args) throws SQLException {
    Connection conn = null;
    PreparedStatement pstm = null;
    try {
        conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM", "SYSDBA", "SYSDBA");
        //设置非自动提交
        conn.setAutoCommit(false);
        //创建PreparedStatement对象
        pstm = conn.prepareStatement("insert into tb_stu(name) values(?);");
        //循环添加批处理数据
        for (int i = 0; i < 1000; i++) {
            pstm.setString(1, "" + i);
            pstm.addBatch();
            //每100条执行一次执行操作
            if (i / 100 == 0) {
                //执行批量插入
                pstm.executeBatch();
                //清空
                pstm.clearBatch();
                //执行事务提交
                conn.commit();
            }
        }
        //执行批量插入
        pstm.executeBatch();
        //清空
        pstm.clearBatch();
        //提交事务
        conn.commit();
    } catch (Exception e) {
        if (!conn.isClosed()) {
            //出现异常,回滚事务
            conn.rollback();
            System.out.println("提交失败,回滚!");
            //关闭非自动提交
            conn.setAutoCommit(true);
        }
    } finally {
        if (pstm != null) {
            //关闭操作对象
            pstm.close();
        }
    }
}

CallableStatement 示例

CallableStatement存在三种类型的参数IN、OUT和INOUT。

  • IN:创建SQL语句时其参数值未知。使用setXXX()方法将值绑定到IN参数。
  • OUT:由SQL语句返回的参数值。使用registerOutParameter()注册OUT参数值类型,可以使用getXXX()方法从OUT参数中检索值。
  • INOUT:提供输入和输出值的参数。使用setXXX()方法绑定变量并使用getXXX()方法检索值。

示例1: 使用setXXX()方法将值绑定到IN参数

java
public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM","SYSDBA","SYSDBA");

    //创建一个 IN 类型参数的存储过程
    conn.createStatement().execute("create procedure p_in(p_id in int,p_name in varchar) as " +
            "begin " +
            "   update tb_stu set name=p_name where id=p_id; " +
            "end;");
    //创建一个CallableStatement对象
    CallableStatement cstm = conn.prepareCall("call p_in(?,?);");
    //使用setXxx()方法给参数传值
    cstm.setInt(1,1);
    cstm.setString(2,"zs");
    //执行
    cstm.execute();

    cstm.close();
    conn.close();
}

示例2: 使用registerOutParameter()注册OUT参数值类型

java
public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM","SYSDBA","SYSDBA");

    //创建一个 OUT 类型参数的存储过程
    conn.createStatement().execute("create procedure p_out(rs out varchar) as " +
            "begin " +
            "   select name into rs from tb_stu where id=1; " +
            "end;");
    //创建一个CallableStatement对象
    CallableStatement cstm = conn.prepareCall("call p_out(?);");
    //使用registerOutParameter()注册OUT类型参数的输出数据类型
    cstm.registerOutParameter(1,Types.VARCHAR);
    //执行
    cstm.execute();
    //获取结果
    String rs = cstm.getString(1);
    System.out.println(rs);

    cstm.close();
    conn.close();
}

示例3:除了使用参数下标绑定参数以外,CallableStatement也支持使用参数名绑定参数

java
public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM","SYSDBA","SYSDBA");

    //创建一个 IN 类型参数的存储过程
    conn.createStatement().execute("create procedure p_in(p_id in int,p_name in varchar) as " +
            "begin " +
            "   update tb_stu set name=p_name where id=p_id; " +
            "end;");
    //创建一个CallableStatement对象
    CallableStatement cstm = conn.prepareCall("call p_in(:a,:b);");
    //使用setXxx()方法给参数传值
    cstm.setInt("a",1);
    cstm.setString("b","zs");
    //执行
    cstm.execute();

    cstm.close();
    conn.close();
}

注意

  • 不支持参数下标绑定和参数名绑定混合使用

连接事务管理

以下为使用 setAutoCommit() 方法控制事务提交的示例代码:

示例:

java
public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM", "SYSDBA", "SYSDBA");
    //设置事务为非自动提交模式
    conn.setAutoCommit(false);
    //创建数据库Statement对象
    Statement stm = conn.createStatement();
    //数据库事务执行SQL语句
    String sql = "insert into tb_stu(name) values('zs');";
    //执行静态SQL语句
    stm.execute(sql);
    //数据库预处理SQL语句
    PreparedStatement pstm = conn.prepareStatement("update tb_stu set name='ls' where id=?");
    //预处理SQL语句参数赋值
    pstm.setInt(1, 1);
    //执行预处理SQL语句
    pstm.execute();
    //提交事务
    conn.commit();
    //删除表中指定行数据
    stm.execute("delete from tb_stu where id=1;");
    //事务回滚方法
    conn.rollback();
}

上述代码中执行提交事务操作,执行静态SQL语句与执行预处理SQL语句对数据库的更改将永久生效;而后执行的删除表中指定行数据操作,因其后调用的rollback() 方法,delete命令对数据库的数据更改将被回滚掉,故而对数据库的删除操作不会生效。

连接事务控制

示例:连接事务控制接口Savepoint使用

java
public static void main(String[] args) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:xugu://localhost:5138/SYSTEM", "SYSDBA", "SYSDBA");
    //设置非自动提交
    conn.setAutoCommit(false);
    //创建Statement对象
    Statement stm = conn.createStatement();
    //执行SQL命令
    stm.execute("insert into tb_stu(name) values('zs');");
    stm.execute("insert into tb_stu(name) values('ls');");
    //设置事务回滚点save1
    java.sql.Savepoint save1 = conn.setSavepoint("save_1");
    stm.execute("insert into tb_stu(name) values('ww');");
    //设置事务回滚点save2
    java.sql.Savepoint save2 = conn.setSavepoint("save_2");
    stm.execute("insert into tb_stu(name) values('zl');");
    //设置事务回滚点save3
    java.sql.Savepoint save3 = conn.setSavepoint("save_3");
    stm.execute("insert into tb_stu(name) values('cq');");
    //回滚事务到回滚点save3
    conn.rollback(save3);
    conn.commit();
}

上述代码段中,事务执行语句sql5将被回滚掉。