JDBC 示例说明
=======================

在所提供的用例中，使用的数据库信息为，用户名：system；密码：manager;数据库名：test；端口号：54321

- `DataSource 示例`_
- `ConnectionPooling 示例`_
- `Statement 示例`_
- `PreparedStatement 示例`_
- `CallableStatement 示例`_
- `ResultSet 示例`_
- `BLOB 示例`_
- `CLOB 示例`_
- `Transaction 示例`_
- `DatabaseMetadata 示例`_
- `调用存储过程示例`_
- `interval year[(n)] to month 示例`_
- `interval day[(n)] to second[(m)] 示例`_

您可前往人大金仓官网下载 `JDBC测试用例 <https://kingbase.oss-cn-beijing.aliyuncs.com/KES_INTERFACE/testyongli/jdbc/jdbc.zip>`_ 。

DataSource 示例
---------------------------

.. container:: EXAMPLE

  **例 12-1. DataSource 的使用**

  .. code:: SCREEN

     import java.sql.Connection;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;
     import java.util.Hashtable;

     import javax.naming.Context;
     import javax.naming.InitialContext;
     import javax.naming.NamingException;
     import javax.sql.DataSource;

     import com.kingbase8.jdbc3.Jdbc3SimpleDataSource;

     public class testDataSource 
     {
         public static void main(String[] args) throws NamingException, 
         SQLException 
         {
             /* 初始化数据源 */
             Jdbc3SimpleDataSource ds = new Jdbc3SimpleDataSource();
             ds.setServerName("localhost");
             ds.setDatabaseName("test");
             ds.setUser("system");
             ds.setPassword("manager");
             ds.setPortNumber(54321);
             Context ctx = null;
             try
             {
                 Hashtable env = new Hashtable(5);
                 env.put(Context.INITIAL_CONTEXT_FACTORY,
                     "com.sun.jndi.fscontext.RefFSContextFactory");
                 env.put(Context.PROVIDER_URL, "file:/job/jndi");
                 ctx = new InitialContext(env);
             }
             catch (NamingException ne)
             {
                 ne.printStackTrace();
             }
             /* 将"DataSource"名称绑定到数据源对象 */
             ctx.rebind("DataSource", ds);
             
             Context ctx2 = null;
             try
             {
                 Hashtable env = new Hashtable(5);
                 env.put(Context.INITIAL_CONTEXT_FACTORY,
                     "com.sun.jndi.fscontext.RefFSContextFactory");
                 env.put(Context.PROVIDER_URL, "file:/job/jndi");
                 ctx2 = new InitialContext(env);
             }

             catch (NamingException ne)
             {
                 ne.printStackTrace();
             }
             /* 在上下文中检索"DataSource"对象 */
             DataSource ds2 = (DataSource) ctx2.lookup("DataSource");
             
             /* 获取连接对象 */
             Connection conn = ds2.getConnection();
             /* 建立语句对象 */
             Statement stmt = conn.createStatement();
             /* 执行语句 */
             stmt.executeUpdate("create table dataSource (id int)");
             stmt.executeUpdate("insert into dataSource values (1)");
             ResultSet rs = stmt.executeQuery("select * from dataSource");
             while(rs.next())
             {
                 System.out.println("id:"+ rs.getInt(1));
             }
             stmt.executeUpdate("drop table dataSource");
             rs.close();
             stmt.close();
             conn.close();
         }
     }
                 

ConnectionPooling 示例
------------------------------------

.. container:: EXAMPLE

  **例 12-2. ConnectionPooling 的使用**

  .. code:: SCREEN

     import java.sql.Connection;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     import com.kingbase8.jdbc3.Jdbc3PoolingDataSource;

     public class testPooling 
     {
         public static void main(String[] args) throws SQLException 
         {
             /* 初始化数据源 */
             Jdbc3PoolingDataSource ds = new Jdbc3PoolingDataSource();
             ds.setDataSourceName("A Data Source");
             ds.setServerName("localhost");
             ds.setDatabaseName("test");
             ds.setUser("system");
             ds.setPassword("manager");
             ds.setMaxConnections(10);
             ds.setInitialConnections(10);
             ds.setPortNumber(54321);
             /* 获取连接对象 */
             Connection conn = ds.getConnection();
             Statement stmt = conn.createStatement();
             stmt.executeUpdate("create table pool (id int)");
             stmt.executeUpdate("insert into pool values (1)");
             ResultSet rs = stmt.executeQuery("select * from pool");
             while(rs.next())
             {
                 System.out.println("id:"+ rs.getInt(1));
             }
             stmt.executeUpdate("drop table pool");
             rs.close();
             stmt.close();
             conn.close();
             ds.close();
         }
     }
                 

Statement 示例
-------------------------

.. container:: EXAMPLE

  **例 12-3. Statement 的使用**

  .. code:: SCREEN

     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testStatement 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         protected String create_table = "create table orders(ORDER_ID SERIAL, "
             + "ISBN int, CUSTOMERID varchar(20))";

         /* 加载驱动 */
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         public static void main(String[] args) throws ClassNotFoundException, 
             SQLException, InterruptedException 
         {
             testStatement test = new testStatement();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.getGeneratedKeys();
             test.close();
         }
         
         /* 建立连接 */
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         /* 建立语句对象 */
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         /* 执行建表语句 */
         protected void table() throws SQLException
         {
             statement.executeUpdate(create_table);
         }
         
         protected void getGeneratedKeys() throws SQLException
         {
             /* 执行SQL语句并返回所有列 */
             int rows = statement.executeUpdate("insert into orders (ISBN," +
                 "CUSTOMERID) VALUES (195123018,'BILLING')"
                 , Statement.RETURN_GENERATED_KEYS);
             System.out.println("rows:" + rows);
             ResultSet rs = null;
             rs = statement.getGeneratedKeys();
             boolean b = rs.next();
             if (b)
             {
                 System.out.println(rs.getString(1));
             }
             rs.close();
             /* 执行SQL语句并返回数组中的指定列 */
             statement.executeUpdate("delete from orders");
             boolean result = statement.execute("insert into orders (ISBN," +
                 "CUSTOMERID)  VALUES (195123018,'BILLING')"
                 , Statement.RETURN_GENERATED_KEYS);
             System.out.println("result:"+result);

             rs = statement.getGeneratedKeys();
             boolean c = rs.next();
             if (c)
             {
                 System.out.println(rs.getString(1));
             }
             rs.close();
             
             statement.executeUpdate("delete from orders");
             String keyColumn[] = {"order_id"};
             int row = statement.executeUpdate("insert into orders (ISBN," +
                 "CUSTOMERID) VALUES (195123018,'BILLING')", keyColumn);
             System.out.println("row:"+row);
             rs = statement.getGeneratedKeys();
             boolean d = rs.next();
             if(d)
             {
                 System.out.println(rs.getString(1));
             }
             rs.close();

             
             statement.executeUpdate("delete from orders");
             String keyColumn1[] = {"order_id"};
             boolean result1 = statement.execute("insert into orders (ISBN," +
                 "CUSTOMERID) VALUES (195123018,'BILLING')", keyColumn1);
             System.out.println("result1:"+result1);
             rs = statement.getGeneratedKeys();
             boolean e = rs.next();
             if(e)
             {
                 System.out.println(rs.getString(1));
             }
             rs.close();
         }
         
         /* 关闭语句、连接对象 */
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table orders");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }
                 

PreparedStatement 示例
----------------------------------

.. container:: EXAMPLE

  **例 12-4. PreparedStatement 的使用**

  .. code:: SCREEN

     import java.math.BigDecimal;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ParameterMetaData;
     import java.sql.PreparedStatement;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testPreparedStatement 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         protected enumn[] employee = new enumn[5];
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         public static void main(String[] args) throws SQLException, 
             ClassNotFoundException, InterruptedException 
         {
             testPreparedStatement test = new testPreparedStatement();
             test.initEmployee();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.preparedStatement();
             test.getParameterMetaData();
             test.close();
             
         }
         
         /* 初始化数据 */
         protected void initEmployee()
         {
             for(int i = 0; i < employee.length; i++)
             {
                 employee[i] = new enumn();
                 employee[i].id = i;
                 employee[i].salary = new BigDecimal("100." + i);
             }
         }
         
         /* 建立连接 */
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         /* 建立语句对象 */
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         /* 执行建表和插入语句 */
         protected void table() throws SQLException
         {
             statement.executeUpdate("create table employees (ID int not null " +
                 "primary key, SALARY numeric(9,5))");
             for(int i = 0; i < 5 ; i++)
             {
                 statement.executeUpdate("insert into employees values (" + i + 
                 "," + "100.10" + ")");
             }
         }
         
         protected void preparedStatement() throws SQLException
         {
             /* 使用PreparedStatement更新语句 */
             PreparedStatement preparedStatement = connection.prepareStatement(
                 "UPDATE employees SET SALARY = ? WHERE ID = ?");
             for(int i = 0; i < employee.length; i++)
             {
                 preparedStatement.setBigDecimal(1, employee[i].salary);
                 preparedStatement.setInt(2, employee[i].id);
                 preparedStatement.executeUpdate();
             }
             
             /* 查询数据 */
             ResultSet rs = statement.executeQuery("select SALARY from employees");
             while(rs.next())
             {
                 System.out.println(rs.getBigDecimal(1));
             }
             rs.close();
             preparedStatement.close();
         }
         
         /* 获取参数元信息 */
         protected void getParameterMetaData() throws SQLException
         {
             statement.executeUpdate("delete from employees");
             PreparedStatement preparedStatement = connection.prepareStatement(
                 "insert into employees (ID, SALARY) values (?,?)");
             ParameterMetaData pmd = preparedStatement.getParameterMetaData();
             int parameterCount = pmd.getParameterCount();
             System.out.println(parameterCount);
             preparedStatement.close();
         }
         
         /* 删除表，关闭语句、连接对象 */
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table employees");
             if(statement != null)
             {
                 statement.close();
             }

             if(connection != null)
             {
                 connection.close();
             }
         }
     }

     class enumn
     {
         BigDecimal salary;
         int id;
     }
                 

CallableStatement 示例
----------------------------------

.. container:: EXAMPLE

  **例 12-5. CallableStatement 的使用**

  .. code:: SCREEN

     import java.sql.CallableStatement;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.SQLException;
     import java.sql.Statement;

     import com.kingbase8.jdbc.KbCallableStatement;

     public class testCallableStatement 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         

         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         protected void table() throws SQLException
         {
             
             statement.executeUpdate("create table callable (number int, " +
                 "xm char(20), gz float)");
             for(int i = 0; i < 5 ; i++)
             {
                 statement.executeUpdate("insert into callable values ("+ i 
                 + "," + "'a" + i + "'," + 123.1 + ")");
             }
         }
         
         public static void main(String[] args) throws ClassNotFoundException, 
             SQLException, InterruptedException 
         {
             testCallableStatement test = new testCallableStatement();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.callableStatement();
             test.close();
         }
         
         public void callableStatement() throws SQLException
         {
             /* oracle兼容模式下 */
             String sql = "create or replace procedure procName (inout id "
                     + "int, in name char(20),out salary float) as "
                     + "begin "
                     + "select number into id from callable where number "
                     + "= id and xm = name;"
                     + "select gz into salary from callable where number "
                     + "= id and xm = name;"
                     + "end;";
             /* PG兼容模式下 */
             /* String sql = "create or replace function procName (inout id "
              *        + "int, in name char(20),out salary float) as '"
              *        + "begin "
              *        + "select number into id from callable where number "
              *        + "= id and xm = name;"
              *        + "select gz into salary from callable where number "
              *        + "= id and xm = name;"
              *        + "end;' LANGUAGE plpgsql;"; 
              */
             
             /* 按索引绑定 */
             statement.execute(sql);
             CallableStatement cstmt = connection.prepareCall(
                 "{call procName(?,?,?)}");
             cstmt.setInt(1, 2);
             cstmt.setString(2, "a2");
             cstmt.registerOutParameter(1,java.sql.Types.INTEGER);
             cstmt.registerOutParameter(3, java.sql.Types.REAL);
             cstmt.execute();
             System.out.println(cstmt.getInt(1));
             System.out.println(cstmt.getFloat(3));

             /* 标准接口按参数名绑定 */
             CallableStatement cstmt2 = connection.prepareCall(
                 "{call procName(?,?,?)}");
             cstmt2.registerOutParameter("id",java.sql.Types.INTEGER);
             cstmt2.registerOutParameter("salary",java.sql.Types.REAL);
             cstmt2.setInt("id",2);
             cstmt2.setString("name", "a2");
             cstmt2.execute();
             System.out.println(cstmt2.getInt("id"));
             System.out.println(cstmt2.getFloat("salary"));

             /* 私有接口按参数名绑定 */
             KbCallableStatement cstmt3 = (KbCallableStatement) connection.prepareCall(
                 "{call procName(:id,:name,:salary)}");
             cstmt3.registerOutParameterAtName("id",java.sql.Types.INTEGER);
             cstmt3.registerOutParameterAtName("salary",java.sql.Types.REAL);
             cstmt3.setIntAtName("id",2);
             cstmt3.setStringAtName("name", "a2");
             cstmt3.execute();
             System.out.println(cstmt.getInt(1));
             System.out.println(cstmt.getFloat(3));
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table callable");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }           

.. container:: EXAMPLE

  **例 12-6. oracle兼容模式下，refcursor 为 OUT 参数和 RETURN
  参数时，CallableStatement 的使用**

  .. code:: SCREEN

     import java.sql.CallableStatement;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;
     import java.sql.Types;

     public class testCallableStatement 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/TEST";
         protected Connection connection = null;
         protected Statement statement = null;
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         protected void table() throws SQLException
         {
             statement.executeUpdate("create table testrs (id integer primary " +
                 "key)");
             for(int i = 0; i < 5 ; i++)
             {
                 statement.executeUpdate("insert into testrs values (" + i + ")");
             }
         }
         
         public static void main(String[] args) throws ClassNotFoundException, 
         SQLException, InterruptedException 
         {
             testCallableStatement test = new testCallableStatement();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.callableStatement();
             test.close();
         }
         
         public void callableStatement() throws SQLException
         {
             /* 函数，refcursor作为返回值 */
             statement.execute("CREATE OR REPLACE INTERNAL FUNCTION "
                     + "testssys_getRefcursor() RETURNS refcursor AS '"
                     + "declare v_resset refcursor; "
                     + "begin "
                     + "open v_resset for select id from testrs order by id; "
                     + "return v_resset; "
                     + "end;' LANGUAGE plsql;");
             /* 存储过程，refcursor作为OUT参数 */
             statement.execute("create or replace procedure "
                     + "testssys_demo(v_temp out refcursor) as \n"
                     + "begin \n"
                     + "open v_temp for select id from testrs; \n"
                     + "end; ");
             /* 开启非自动提交模式 */
             connection.setAutoCommit(false);
             /* 调用函数 */
             CallableStatement call = connection.prepareCall(
                     "{ ? = call testssys_getRefcursor() }");
             call.registerOutParameter(1, Types.REF_CURSOR);
             call.execute();
             ResultSet rs = (ResultSet) call.getObject(1);
             System.out.println("testssys_getRefcursor:");
             while(rs.next()) {
                 System.out.println(rs.getInt(1));
             }
             /* 调用存储过程 */
             CallableStatement call2 = connection.prepareCall(
                     "{call testssys_demo (?)}");
             call2.registerOutParameter(1, Types.REF_CURSOR);
             call2.execute();
             ResultSet rs2 = (ResultSet) call2.getObject(1);
             System.out.println("testssys_demo:");
             while(rs2.next()){
                 System.out.println(rs2.getInt(1));
             }
             connection.commit();
             connection.setAutoCommit(true);
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table testrs");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }
                 

  **例 12-7. PG兼容模式下，refcursor 为 OUT 参数和 RETURN
  参数时，CallableStatement 的使用**

  .. code:: SCREEN

     import java.sql.CallableStatement;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;
     import java.sql.Types;

     public class testCallableStatement
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;

         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }

         protected void connection(String url) throws SQLException,
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }
         }

         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }

         protected void table() throws SQLException
         {
             statement.executeUpdate("create table testrs (id integer primary " +
                 "key)");
             for(int i = 0; i < 5 ; i++)
             {
                 statement.executeUpdate("insert into testrs values (" + i + ")");
             }
         }

         public static void main(String[] args) throws ClassNotFoundException,
         SQLException, InterruptedException
         {
             testCallableStatement test = new testCallableStatement();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.callableStatement();
             test.close();
         }

         public void callableStatement() throws SQLException
         {
             statement.execute("CREATE OR REPLACE FUNCTION "
                     + "testssys_getRefcursor() RETURNS refcursor AS '"
                     + "declare v_resset refcursor; "
                     + "begin "
                     + "open v_resset for select id from testrs order by id; "
                     + "return v_resset; "
                     + "end;' LANGUAGE plpgsql;");
             statement.execute("create or replace procedure "
                     + "testssys_demo(v_temp inout refcursor) as '\n"
                     + "begin \n"
                     + "open v_temp for select id from testrs; \n"
                     + "end;' LANGUAGE plpgsql;");
             connection.setAutoCommit(false);
             CallableStatement call = connection.prepareCall(
                     "{ ? = call testssys_getRefcursor() }");
             call.registerOutParameter(1, Types.REF_CURSOR);
             call.execute();
             ResultSet rs = (ResultSet) call.getObject(1);
             System.out.println("testssys_getRefcursor:");
             while(rs.next()) {
                 System.out.println(rs.getInt(1));
             }
             CallableStatement call2 = connection.prepareCall(
                     "call testssys_demo (?)");
             call2.setObject(1, null);
             call2.registerOutParameter(1, Types.REF_CURSOR);
             call2.execute();
             ResultSet rs2 = (ResultSet) call2.getObject(1);
             System.out.println("testssys_demo:");
             while(rs2.next()){
                 System.out.println(rs2.getInt(1));
             }
             connection.commit();
             connection.setAutoCommit(true);
         }

         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table testrs");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }

.. container:: EXAMPLE

  **例 12-8. oracle兼容模式下，存储过程返回多结果集
  时，CallableStatement 的使用**

  .. code:: SCREEN

     import java.sql.CallableStatement;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;
     import java.sql.Types;

     public class testCallableStatement 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/TEST";
         protected Connection connection = null;
         protected Statement statement = null;
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }
         }
         
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         protected void table() throws SQLException
         {
             statement.executeUpdate("create table testrs (id integer primary " +
                 "key)");
             for(int i = 0; i < 5 ; i++)
             {
                 statement.executeUpdate("insert into testrs values (" + i + ")");
             }
         }
         
         public static void main(String[] args) throws ClassNotFoundException, 
         SQLException, InterruptedException 
         {
             testCallableStatement test = new testCallableStatement();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.callableStatement();
             test.close();
         }
         
         public void callableStatement() throws SQLException
         {
             /* 创建存储过程 */
             statement.execute("create or replace procedure "
                     + "testssys_demo(v_temp out refcursor) as \n"
                     + "begin \n"
                     + "select * from  testrs;"
                     + "open v_temp for select id from testrs; \n"
                     + "end; ");
             /* 开启非自动提交模式 */
             connection.setAutoCommit(false);
             CallableStatement call2 = connection.prepareCall(
                     "{call testssys_demo (?)}");
             call2.registerOutParameter(1, Types.REF_CURSOR);
             call2.execute();
             /* 获取存储过程OUT参数的值 */
             ResultSet rs2 = (ResultSet) call2.getObject(1);
             System.out.println("testssys_demo:");
             while(rs2.next()){
                 System.out.println(rs2.getInt(1));
             }
             /* 获取存储过程中查询语句返回的值 */
             rs2 = call2.getResultSet();
             while(rs2.next()){
                 System.out.println(rs2.getInt(1));
             }
             /* 提交事务 */
             connection.commit();
             /* 开启自动提交模式 */
             connection.setAutoCommit(true);
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table testrs");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }

ResultSet 示例
-------------------------

.. container:: EXAMPLE

  **例 12-9. ResultSet 的使用**

  .. code:: SCREEN


     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ResultSet;
     import java.sql.ResultSetMetaData;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testResultSet 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         protected void table() throws SQLException
         {
             statement.executeUpdate("create table table1(id int primary key," +
                     "name char(10))");
             statement.executeUpdate("insert into table1 values (1,'KingbaseES')");
         }
         
         public static void main(String[] args) throws ClassNotFoundException,
             SQLException, InterruptedException 
         {
             testResultSet test = new testResultSet();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.resultSet();
             test.updataResultSet();
             test.close();
         }
         
         protected void resultSet() throws SQLException
         {
             /* 查询并返回结果集 */
             ResultSet rs = statement.executeQuery("select * from table1");
             while(rs.next())
             {
                 System.out.println(rs.getInt(1));
             }
             /* 获取结果集元信息对象 */
             ResultSetMetaData rsmd = rs.getMetaData();
             /* 获取第一列的类型名称 */
             System.out.println(rsmd.getColumnTypeName(1));
             rs.close();
         }
         
         /* 通过结果集更新数据 */
         protected void updataResultSet() throws SQLException
         {
             Statement stmt = connection.createStatement(
                 ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
             ResultSet rs = stmt.executeQuery("select * from table1");
             rs.next();
             System.out.println("update before: " + rs.getInt(1));
             rs.updateInt(1, 21);
             rs.updateRow();
             System.out.println("update after: " + rs.getInt(1));
             rs.close();
             stmt.close();
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table table1");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }

                 

BLOB 示例
----------------------

.. container:: EXAMPLE

  **例 12-10. oracle 兼容模式下，BLOB 的使用**

  .. code:: SCREEN

     import java.io.ByteArrayInputStream;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.OutputStream;
     import java.io.StringWriter;
     import java.sql.Blob;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.PreparedStatement;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testBlob 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         protected String source = "Welcome to Kingbase!";
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         /* 创建表 */
         protected void table() throws SQLException
         {
             statement.executeUpdate("create table blob_table (col1 Blob, " +
                     "col2 Blob, col3 Blob)");
         }
         
         /* 插入数据 */
         protected void insertBlob() throws SQLException
         {
             PreparedStatement pstmt = connection.prepareStatement(
                     "insert into blob_table values (?,?,?)");
             InputStream read = new ByteArrayInputStream(source.getBytes());
             InputStream read1 = new ByteArrayInputStream(source.getBytes());
             InputStream read2 = new ByteArrayInputStream(source.getBytes());
             pstmt.setBlob(1, read);
             pstmt.setBlob(2, read1);
             pstmt.setBlob(3, read2);
             pstmt.executeUpdate();
             pstmt.close();
         }
         
         /* 查询数据 */
         protected void queryBlob() throws SQLException, IOException
         {
             String sql_select = "select * from blob_table";
             ResultSet resultSet = statement.executeQuery(sql_select);
             int count = 1;
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 /* 获取Blob对象的内容 */
                 String blob1 = new String(resultSet.getBytes(1));
                 String blob2 = new String(resultSet.getBytes(2));
                 String blob3 = new String(resultSet.getBytes(3));
                 System.out.println("blob1:" + blob1);
                 System.out.println("blob2:" + blob2);
                 System.out.println("blob3:" + blob3);
                 count++;
             }
             resultSet.close();
             
             count = 1;
             resultSet = statement.executeQuery(sql_select);
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 for(int i = 0; i < 3; i++)
                 {
                     /* 获取Blob对象 */
                     Blob blob = resultSet.getBlob(i+1);
                     /* 将此blob实例的值作为流 */
                     InputStream input = blob.getBinaryStream();
                     StringWriter sWriter = new StringWriter();
                     int j = -1;
                     while((j = input.read()) != -1)
                     {
                         sWriter.write(j);
                     }
                     String finalBlob = new String(sWriter.getBuffer());
                     System.out.println(finalBlob);
                 }
                 count++;
             }
             resultSet.close();
             
         }
         
         protected void updateBlob() throws SQLException, IOException
         {
             String sql_select = "select * from blob_table for update";
             ResultSet resultSet = statement.executeQuery(sql_select);
             if(resultSet.next())
             {
                 Blob blob = resultSet.getBlob(1);
                 /* 获取可用于写入此blob对象所代表的BLOB值的流 */
                 OutputStream output = blob.setBinaryStream(blob.length()
                  + 1);
                 String temp = "Welcome to Kingbase!";
                 byte[] tempByte = temp.getBytes();
                 output.write(tempByte);
                 output.close();         
                 
                 blob = resultSet.getBlob(2);
                 temp = "Hello, Kingbase!";
                 /* 将给定的字节数组从位置(blob.length() + 1)开始写入Blob对象 */
                 blob.setBytes(blob.length() + 1, temp.getBytes());
                 
                 resultSet = statement.executeQuery(sql_select);
                 if(resultSet.next()) {
                     System.out.println("更新后的记录");
                     System.out.println(new String(resultSet.getBytes(1)));
                     System.out.println(new String(resultSet.getBytes(2)));
                     System.out.println(new String(resultSet.getBytes(3)));
                 }
             }
             resultSet.close();
         }
         
         public static void main(String[] args) throws ClassNotFoundException,
             SQLException, InterruptedException, IOException 
         {
             testBlob test = new testBlob();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.insertBlob();
             test.queryBlob();
             test.updateBlob();
             test.close();
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table blob_table");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }
                 

  **例 12-11 PG 兼容模式下，BLOB 的使用**

  .. code:: SCREEN

     import java.io.ByteArrayInputStream;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.OutputStream;
     import java.io.StringWriter;
     import java.sql.Blob;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.PreparedStatement;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testBlob
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         protected String source = "Welcome to Kingbase!";

         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }

         protected void connection(String url) throws SQLException,
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }
             connection.setAutoCommit(false);
         }

         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }

         protected void table() throws SQLException
         {
             statement.executeUpdate("create table blob_table (col1 oid, " +
                     "col2 oid, col3 oid)");
         }

         protected void insertBlob() throws SQLException
         {
             PreparedStatement pstmt = connection.prepareStatement(
                     "insert into blob_table values (?,?,?)");
             InputStream read = new ByteArrayInputStream(source.getBytes());
             InputStream read1 = new ByteArrayInputStream(source.getBytes());
             InputStream read2 = new ByteArrayInputStream(source.getBytes());
             pstmt.setBlob(1, read);
             pstmt.setBlob(2, read1);
             pstmt.setBlob(3, read2);
             pstmt.executeUpdate();
             pstmt.close();
         }

         protected void queryBlob() throws SQLException, IOException
         {
             String sql_select = "select * from blob_table";
             ResultSet resultSet = statement.executeQuery(sql_select);
             int count = 1;
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 Blob blob1 = resultSet.getBlob(1);
                 Blob blob2 = resultSet.getBlob(2);
                 Blob blob3 = resultSet.getBlob(3);
                 System.out.println("blob1:" + new String(blob1.getBytes(1, (int) 
                 blob1.length())));
                 System.out.println("blob2:" + new String(blob2.getBytes(1, (int) 
                 blob2.length())));
                 System.out.println("blob3:" + new String(blob3.getBytes(1, (int) 
                 blob3.length())));
                 count++;
             }
             resultSet.close();

             count = 1;
             resultSet = statement.executeQuery(sql_select);
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 for(int i = 0; i < 3; i++)
                 {
                     Blob blob = resultSet.getBlob(i+1);
                     InputStream input = blob.getBinaryStream();
                     StringWriter sWriter = new StringWriter();
                     int j = -1;
                     while((j = input.read()) != -1)
                     {
                         sWriter.write(j);
                     }
                     String finalBlob = new String(sWriter.getBuffer());
                     System.out.println(finalBlob);
                 }
                 count++;
             }
             resultSet.close();
         }

         /* 更新大对象 */
         protected void updateBlob() throws SQLException, IOException
         {
             String sql_select = "select * from blob_table for update";
             ResultSet resultSet = statement.executeQuery(sql_select);
             if(resultSet.next())
             {
                 Blob blob = resultSet.getBlob(1);
                 /* 获取可用于写入此blob对象所代表的BLOB值的流 */
                 OutputStream output = blob.setBinaryStream(blob.length()
                  + 1);
                 String temp = "Welcome to Kingbase!";
                 byte[] tempByte = temp.getBytes();
                 output.write(tempByte);
                 output.close();

                 blob = resultSet.getBlob(2);
                 temp = "Hello, Kingbase!";
                 /* 将给定的字节数组从位置(blob.length() + 1)开始写入Blob对象 */
                 blob.setBytes(blob.length() + 1, temp.getBytes());

                 resultSet = statement.executeQuery(sql_select);
                 if(resultSet.next()) {
                     System.out.println("更新后的记录");
                     System.out.println(new String(resultSet.getBlob(1).getBytes(1, 
                     (int) resultSet.getBlob(1).length())));
                     System.out.println(new String(resultSet.getBlob(2).getBytes(1, 
                     (int) resultSet.getBlob(2).length())));
                     System.out.println(new String(resultSet.getBlob(3).getBytes(1, 
                     (int) resultSet.getBlob(3).length())));
                 }
             }
             resultSet.close();
         }

         public static void main(String[] args) throws ClassNotFoundException,
             SQLException, InterruptedException, IOException
         {
             testBlob test = new testBlob();
             test.Driver();
             /* 创建连接并开启事务 */
             test.connection(Url);
             test.statement();
             test.table();
             /* PG模式下，大对象的操作需在事务内执行 */
             test.insertBlob();
             test.queryBlob();
             test.updateBlob();
             test.close();
         }

         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table blob_table");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }

CLOB 示例
----------------------------

.. container:: EXAMPLE

  **例 12-12. oracle 兼容模式下 CLOB 的使用**

  .. code:: SCREEN

     import java.io.IOException;
     import java.io.OutputStream;
     import java.io.Reader;
     import java.io.StringReader;
     import java.io.StringWriter;
     import java.io.Writer;
     import java.sql.Clob;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.PreparedStatement;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testClob 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         protected String source = "Welcome to Kingbase!";
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         protected void table() throws SQLException
         {
             statement.executeUpdate("create table clob_table (col1 Clob, col2 " + 
                 "Clob, col3 Clob)");
         }
         
         protected void insertClob() throws SQLException
         {
             PreparedStatement pstmt = connection.prepareStatement(
                 "insert into clob_table values (?,?,?)");
             StringReader reader = new StringReader(source);
             StringReader reader1 = new StringReader(source);
             StringReader reader2 = new StringReader(source);
             pstmt.setClob(1, reader);
             pstmt.setClob(2, reader1);
             pstmt.setClob(3, reader2);
             pstmt.executeUpdate();
             pstmt.close();
         }
         
         protected void queryClob() throws SQLException, IOException
         {
             String sql_select = "select * from clob_table";
             ResultSet resultSet = statement.executeQuery(sql_select);
             int count = 1;
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 /* 获取Clob对象的内容 */
                 String clob1 = resultSet.getString(1);
                 String clob2 = resultSet.getString(2);
                 String clob3 = resultSet.getString(3);
                 System.out.println("clob1:" + clob1);
                 System.out.println("clob2:" + clob2);
                 System.out.println("clob3:" + clob3);
                 count++;
             }
             resultSet.close();
             
             count = 1;
             resultSet = statement.executeQuery(sql_select);
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 for(int i = 0; i < 3; i++)
                 {
                     /* 获取Clob对象 */
                     Clob clob = resultSet.getClob(i+1);
                     /* 将clob对象的值作为作为字符流检索 */
                     Reader reader = clob.getCharacterStream();
                     /* 将clob的内容写到StringWriter中 */
                     StringWriter sWriter = new StringWriter();
                     int j = -1;
                     while((j = reader.read()) != -1)
                     {
                         sWriter.write(j);
                     }
                     String finalClob = new String(sWriter.getBuffer());
                     System.out.println(finalClob);
                 }
                 count++;
             }
             resultSet.close();
             
         }
         
         /* 更新大对象 */
         protected void updateClob() throws SQLException, IOException
         {
             String sql_select = "select * from clob_table for update";
             ResultSet resultSet = statement.executeQuery(sql_select);
             PreparedStatement pstmt = connection.prepareStatement(
                 "update clob_table set col1=?,col2=?,col3=?");
             if(resultSet.next())
             {
                 Clob clob = resultSet.getClob(1);
                 String temp = "Test has sucessful";
                 System.out.println(resultSet.getString(1).length());
                 /* 追加内容，获取用于将Ascii字符写入到Clob对象表示的CLOB值的流，从位置(clob.length() + 1)开始。*/
                 OutputStream os = clob.setAsciiStream(clob.length() + 1);
                 byte[] tempByte = temp.getBytes();
                 os.write(tempByte);
                 os.close();
                 pstmt.setClob(1, clob);

                 clob = resultSet.getClob(2);
                 /* 追加内容，获取用于将Unicode字符流写入Clob对象表示的CLOB值的流，从位置(clob.length() + 1)开始。*/
                 Writer writer = clob.setCharacterStream(clob.length() + 1);
                 temp = "Welcome to Kingbase!";
                 writer.write(temp);writer.write(temp);
                 writer.close();
                 pstmt.setClob(2, clob);

                 clob = resultSet.getClob(3);
                 temp = "Hello, Kingbase!";
                 /* 追加内容，将给定的字符串temp从(clob.length() + 1)位置写入该Clob对象。*/
                 clob.setString(clob.length() + 1, temp);
             }
             resultSet = statement.executeQuery(sql_select);
             if(resultSet.next())
             {
                 System.out.println("更新后的记录");
                 System.out.println(resultSet.getString(1));
                 System.out.println(resultSet.getString(2));
                 System.out.println(resultSet.getString(3));
             }
             resultSet.close();
         }
         

         public static void main(String[] args) throws ClassNotFoundException, 
             SQLException, InterruptedException, IOException 
         {
             testClob test = new testClob();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.insertClob();
             test.queryClob();
             test.updateClob();
             test.close();
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table clob_table");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }
                 

  **例 12-13. PG 兼容模式下 CLOB 的使用**

  .. code:: SCREEN

     import java.io.ByteArrayInputStream;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.Reader;
     import java.io.StringWriter;
     import java.sql.Clob;
     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.PreparedStatement;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testClob
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         protected String source = "Welcome to Kingbase!";

         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }

         protected void connection(String url) throws SQLException,
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }
             connection.setAutoCommit(false);
         }

         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }

         protected void table() throws SQLException
         {
             statement.executeUpdate("create table clob_table (col1 oid, col2 " +
                 "oid, col3 oid)");
         }

         protected void insertClob() throws SQLException
         {
             PreparedStatement pstmt = connection.prepareStatement(
                 "insert into clob_table values (?,?,?)");
             InputStream read = new ByteArrayInputStream(source.getBytes());
             InputStream read1 = new ByteArrayInputStream(source.getBytes());
             InputStream read2 = new ByteArrayInputStream(source.getBytes());
             pstmt.setBlob(1, read);
             pstmt.setBlob(2, read1);
             pstmt.setBlob(3, read2);
             pstmt.executeUpdate();
             pstmt.close();
         }

         protected void queryClob() throws SQLException, IOException
         {
             String sql_select = "select * from clob_table";
             ResultSet resultSet = statement.executeQuery(sql_select);
             int count = 1;
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 /* 获取Clob对象 */
                 Clob clob1 = resultSet.getClob(1);
                 Clob clob2 = resultSet.getClob(2);
                 Clob clob3 = resultSet.getClob(3);
                 /* 获取Clob对象的内容 */
                 System.out.println("clob1:" + clob1.getSubString(1, (int) 
                 clob1.length()));
                 System.out.println("clob2:" + clob2.getSubString(1, (int) 
                 clob2.length()));
                 System.out.println("clob3:" + clob3.getSubString(1, (int) 
                 clob3.length()));
                 count++;
             }
             resultSet.close();

             count = 1;
             resultSet = statement.executeQuery(sql_select);
             while(resultSet.next())
             {
                 System.out.println("第" + count + "条记录");
                 for(int i = 0; i < 3; i++)
                 {
                     Clob clob = resultSet.getClob(i+1);
                     /* 将clob对象的值作为作为字符流检索 */
                     Reader reader = clob.getCharacterStream();
                     /* 将clob的内容写到StringWriter中 */
                     StringWriter sWriter = new StringWriter();
                     int j = -1;
                     while((j = reader.read()) != -1)
                     {
                         sWriter.write(j);
                     }
                     String finalClob = new String(sWriter.getBuffer());
                     System.out.println(finalClob);
                 }
                 count++;
             }
             resultSet.close();
         }

         public static void main(String[] args) throws ClassNotFoundException,
             SQLException, InterruptedException, IOException
         {
             testClob test = new testClob();
             test.Driver();
             /* 创建连接并开启事务 */
             test.connection(Url);
             test.statement();
             test.table();
             /* PG模式下，大对象的操作需在事务内执行 */
             test.insertClob();
             test.queryClob();
             test.close();
         }

         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table clob_table");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }



Transaction 示例
----------------------------

.. container:: EXAMPLE

  **例 12-14. Transaction 的使用**

  .. code:: SCREEN

     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Savepoint;
     import java.sql.Statement;

     public class testTransaction 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         protected Statement statement = null;
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         protected void table() throws SQLException
         {
             statement.executeUpdate("create table transaction (number int)");
         }
         
         protected void transactionTest() throws SQLException
         {
             /* 设置为非自动提交模式 */
             connection.setAutoCommit(false);
             Statement stmt = connection.createStatement();
             /* 设置保存点svpt2 */
             Savepoint svpt2 = connection.setSavepoint("SAVEPOINT_2");
             int row1 = stmt.executeUpdate(
                 "INSERT INTO transaction (number) VALUES (1)");
             System.out.println(row1);
             /* 设置保存点svpt1 */
             Savepoint svpt1 = connection.setSavepoint("SAVEPOINT_1");
             int row2 = stmt.executeUpdate(
                 "INSERT INTO transaction (number)  VALUES (2)");
             System.out.println(row2);
             /* 回滚保存点svpt1 */
             connection.rollback(svpt1);
             /* 回滚保存点svpt2 */
             connection.rollback(svpt2);
             /* 提交事务 */ 
             connection.commit();
             ResultSet rs = stmt.executeQuery("select * from transaction");
             while(rs.next())
             {
                 System.out.println(rs.getInt(1));
             }
             rs.close();
             stmt.close();
         }
         
         public static void main(String[] args) throws ClassNotFoundException, 
             SQLException, InterruptedException
         {
             testTransaction test = new testTransaction();
             test.Driver();
             test.connection(Url);
             test.statement();
             test.table();
             test.transactionTest();
             test.close();
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table transaction");
             connection.commit();
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }
                 

.. container:: EXAMPLE

  **例 12-15. autosave 的使用**

  .. code:: SCREEN

     import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.ResultSet;
     import java.sql.SQLException;
     import java.sql.Statement;

     public class testRollbackLevel 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/" +
             "test?autosave=always";
         protected Connection connection = null;
         protected Statement statement = null;
         protected String create_table = "create table orders(id int)";
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         protected void statement() throws SQLException
         {
             statement = connection.createStatement();
         }
         
         public static void main(String[] args) throws ClassNotFoundException, 
             SQLException, InterruptedException 
         {
             testRollbackLevel test = new testRollbackLevel();
             test.Driver();
             test.connection(Url);
             test.statement();

             test.table();
             test.testLevel();
             test.close();
         }
         
         protected void table() throws SQLException
         {
             statement.executeUpdate(create_table);
         }
         
         protected void testLevel() throws SQLException 
         {
             /* 设置为非自动提交模式 */
             connection.setAutoCommit(false);
             try
             {
                 /* 插入正常数据 */
                 statement.execute("insert into orders values(1)");
             }
             catch(SQLException e)
             {
                 
             }
             try
             {
                 /* 插入非法数据，返回异常 */
                 statement.execute("insert into orders values(a)");
             }
             catch(SQLException e)
             {
                 
             }
             try
             {
                 statement.execute("insert into orders values(3)");
             }
             catch(SQLException e)
             {
                 
             }
             /* 提交事务 */
             connection.commit();
             /* 设置为自动提交模式 */
             connection.setAutoCommit(true);
             ResultSet rs = statement.executeQuery("select * from orders");
             while(rs.next())
             {
                 System.out.println(rs.getInt(1));
             }
             rs.close();
             
         }
         
         protected void close() throws SQLException
         {
             statement.executeUpdate("drop table orders");
             if(statement != null)
             {
                 statement.close();
             }
             if(connection != null)
             {
                 connection.close();
             }
         }
     }
                 

DatabaseMetadata 示例
--------------------------------

.. container:: EXAMPLE

  **例 12-16. DatabaseMetadata 的使用**

  .. code:: SCREEN

     import java.sql.Connection;
     import java.sql.DatabaseMetaData;
     import java.sql.DriverManager;
     import java.sql.SQLException;

     public class testDatabaseMetadata 
     {
         protected String Driver = "com.kingbase8.Driver";
         protected static String Url = "jdbc:kingbase8://localhost:54321/test";
         protected Connection connection = null;
         
         protected void Driver() throws ClassNotFoundException
         {
             Class.forName(Driver);
         }
         
         protected void connection(String url) throws SQLException, 
             InterruptedException
         {
             connection = DriverManager.getConnection(url, "system", "manager");
             if(connection != null)
             {
                 System.out.println("connection sucessful!");
             }
             else
             {
                 System.out.println("connection fail!");
             }       
         }
         
         public static void main(String[] args) throws ClassNotFoundException, 
             SQLException, InterruptedException 
         {
             testDatabaseMetadata test = new testDatabaseMetadata();
             test.Driver();
             test.connection(Url);
             test.metaDate();
             test.close();
         }
         
         protected void metaDate() throws SQLException
         {
             /* 获取数据库元信息对象 */
             DatabaseMetaData metaDate = connection.getMetaData();
             /* 通过数据库元信息对象获取连接对象 */
             Connection connection = metaDate.getConnection();
             /* 通过数据库元信息对象获取数据库的主版本号 */
             int DatabaseMajorVersion = metaDate.getDatabaseMajorVersion();
             /* 通过数据库元信息对象获取驱动的主版本号 */
             int JDBCMajorVersion = metaDate.getJDBCMajorVersion();
             System.out.println(JDBCMajorVersion);
         }
         
         protected void close() throws SQLException
         {
             if(connection != null)
             {
                 connection.close();
             }
         }
     }

调用存储过程示例
----------------
     
调用存储过程，使用CallableStatement接口。

.. container:: EXAMPLE


  .. code::

     /**
      * 无返回值call调用格式的函数调用
      *
      * @throws SQLException SQL异常
      */

      /* 按名称绑定的存储过程调用 */
     @Test
     public void testProcParamNames() throws SQLException {
         CallableStatement call = connection.prepareCall( "call proc1(1,?,?)");
         call.setDouble("b", 2);
         call.registerOutParameter("c", Types.VARCHAR);
         call.execute();
         String col3 = call.getString("c");
         assertEquals("a", col3);
         call = connection.prepareCall( "{call proc1(1,?,?)}");
         call.setDouble("b", 2);
         call.registerOutParameter("c", Types.VARCHAR);
         call.execute();
         col3 = call.getString("c");
         assertEquals("a", col3);
     }
 
     /* 含有固定值的按索引绑定的存储过程调用 */
     @Test
     public void testProcParamNames2() throws SQLException {
         CallableStatement call = connection.prepareCall( "call proc1(?,1,?)");
         call.setInt(1, 2);
         call.registerOutParameter(2, Types.VARCHAR);
         call.execute();
         String col3 = call.getString(2);
         assertEquals("a", col3);
         call = connection.prepareCall( "{call proc1(?,1,?)}");
         call.setInt(1, 2);
         call.registerOutParameter(2, Types.VARCHAR);
         call.execute();
         col3 = call.getString(2);
         assertEquals("a", col3);
     } 

     /* 含有固定值的按名称绑定的函数调用 */
     @Test
     public void testFuncParamNamesWithReturnBindAtName() throws SQLException {
         CallableStatement call = connection.prepareCall( "{? = call func1(?,1,?)}");
         call.registerOutParameter("returnValue", Types.DOUBLE);
         call.setString("a", "1");
         call.registerOutParameter("c", Types.VARCHAR);
         call.execute();
         String col3 = call.getString("c");
         assertEquals("a", col3);
     }
     
     /* 含有固定值的按索引绑定的函数调用 */
     @Test
     public void testFuncParamNamesWithReturnBindAtIndex() throws SQLException {
         CallableStatement call = connection.prepareCall( "{? = call func1(?,1,?)}");
         call.registerOutParameter(1, Types.DOUBLE);
         call.setString(2, "1");
         call.registerOutParameter(3, Types.VARCHAR);
         call.execute();
         String col3 = call.getString(3);
         assertEquals("a", col3);
     }

interval year[(n)] to month 示例
--------------------------------

.. container:: EXAMPLE

   **例 12-17. 该数据类型只在Oracle兼容模式下可用**

   .. code:: SCREEN

      import com.kingbase8.KBProperty;
      import com.kingbase8.test.TestUtils;
      import com.kingbase8.test.jdbc2.BaseTest4.BinMode;
      import org.junit.After;
      import org.junit.Before;
      import org.junit.Test;
      import org.junit.runner.RunWith;
      import org.junit.runners.Parameterized;

      import java.sql.*;
      import java.util.*;

      import static org.junit.Assert.assertEquals;
      import static org.junit.Assert.assertTrue;

      @RunWith(Parameterized.class)
      public class OracleIntervalTypeTest {

          private Connection con;
          private BinMode binaryMode;

          public OracleIntervalTypeTest(BinMode binaryMode) {
              setBinaryMode(binaryMode);
          }

          @Parameterized.Parameters(name = "binary = {0}")
          public static Iterable<Object[]> data() {
              Collection<Object[]> ids = new ArrayList<Object[]>();
              for (BinMode binaryMode : BinMode.values()) {
                  ids.add(new Object[]{binaryMode});
              }
              return ids;
          }

          protected void updateProperties(Properties props) {
              if (binaryMode == BinMode.FORCE) {
                  // set force binary mode transfer
                  forceBinary(props);
              } else {
                  // set force text mode transfer
                  KBProperty.BINARY_TRANSFER.set(props, false);
              }
          }

          protected void forceBinary(Properties props) {
              KBProperty.PREPARE_THRESHOLD.set(props, -1);
          }

          public final void setBinaryMode(BinMode binaryMode) {
              this.binaryMode = binaryMode;
          }

          @Before
          public void setUp() throws Exception {
              Properties props = new Properties();
              updateProperties(props);
              con = TestUtils.openDB_(props);
      
              TestUtils.createTable_(con, "tyminterval1", "t1 interval year to month");
         }

          @After
          public void tearDown() throws Exception {

              TestUtils.dropTable_(con, "tyminterval1");

              TestUtils.closeDB_(con);
          }

          @Test
          public void testYM() throws SQLException {
              Statement stmt = con.createStatement();
              stmt.execute("SET intervalstyle to sql_standard");
              PreparedStatement ps = con.prepareStatement("insert into tyminterval1 values(?)");
              ps.setObject(1, "12-1");
              ps.execute();
              ps.setString(1, "+20-8");
              ps.execute();
              ps.setObject(1, "-12-1");
              ps.execute();
              Statement st = con.createStatement();
              ResultSet rs = st.executeQuery("select * from tyminterval1");
              ResultSetMetaData rsmd = rs.getMetaData();
              assertEquals(rsmd.getColumnType(1), Types.OTHER);
              assertEquals(rsmd.getColumnTypeName(1), "yminterval");
              assertEquals(rsmd.getColumnClassName(1), "com.kingbase8.jdbc.YMInterval");
              assertEquals(rsmd.getColumnLabel(1), "t1");
              assertEquals(rsmd.getColumnName(1), "t1");
              assertEquals(rsmd.getColumnDisplaySize(1), 5);
              assertEquals(rsmd.getPrecision(1), 2);
              assertEquals(rsmd.getScale(1), 0);
              assertTrue(rs.next());
              assertEquals("12-1", rs.getString(1));
              assertEquals("12-1", rs.getObject(1).toString());
              assertEquals("class com.kingbase8.jdbc.YMInterval", rs.getObject(1).getClass().toString());
              assertTrue(rs.next());
              assertEquals("20-8", rs.getString(1));
              assertEquals("20-8", rs.getObject(1).toString());
              assertTrue(rs.next());
              assertEquals("-12-1", rs.getString(1));
              assertEquals("-12-1", rs.getObject(1).toString());
              rs.close();
              ps.close();
              st.close();
              stmt.close();
          }
      }

interval day[(n)] to second[(m)] 示例
-------------------------------------

.. container:: EXAMPLE
  
   **例 12-18. 该数据类型只在Oracle兼容模式下可用**

   .. code:: SCREEN

      import com.kingbase8.KBProperty;
      import com.kingbase8.test.TestUtils;
      import com.kingbase8.test.jdbc2.BaseTest4.BinMode;
      import org.junit.After;
      import org.junit.Before;
      import org.junit.Test;
      import org.junit.runner.RunWith;
      import org.junit.runners.Parameterized;

      import java.sql.*;
      import java.util.*;

      import static org.junit.Assert.assertEquals;
      import static org.junit.Assert.assertTrue;

      @RunWith(Parameterized.class)
      public class OracleIntervalTypeTest {

          private Connection con;
          private BinMode binaryMode;

          public OracleIntervalTypeTest(BinMode binaryMode) {
              setBinaryMode(binaryMode);
          }
      
          @Parameterized.Parameters(name = "binary = {0}")
          public static Iterable<Object[]> data() {
              Collection<Object[]> ids = new ArrayList<Object[]>();
              for (BinMode binaryMode : BinMode.values()) {
                  ids.add(new Object[]{binaryMode});
              }
              return ids;
          }
      
          protected void updateProperties(Properties props) {
              if (binaryMode == BinMode.FORCE) {
                  // set force binary mode transfer
                  forceBinary(props);
              } else {
                  // set force text mode transfer
                  KBProperty.BINARY_TRANSFER.set(props, false);
              }
          }
      
          protected void forceBinary(Properties props) {
              KBProperty.PREPARE_THRESHOLD.set(props, -1);
          }

          public final void setBinaryMode(BinMode binaryMode) {
              this.binaryMode = binaryMode;
          }

          @Before
          public void setUp() throws Exception {
              Properties props = new Properties();
              updateProperties(props);
              con = TestUtils.openDB_(props);
      
              TestUtils.createTable_(con, "tyminterval3", "t1 interval day to second");

          }

          @After
          public void tearDown() throws Exception {
      
              TestUtils.dropTable_(con, "tyminterval3");

              TestUtils.closeDB_(con);
          }

          @Test
          public void testDS() throws SQLException {
              Statement stmt = con.createStatement();
              stmt.execute("SET intervalstyle to sql_standard");
              PreparedStatement ps = con.prepareStatement("insert into tyminterval3 values(?)");
              ps.setObject(1, "12 12:12:12.111111");
              ps.execute();
              ps.setString(1, "-12 12:12:12.111111");
              ps.execute();
              ps.setObject(1, "12 12:12:12.111111");
              ps.execute();
              Statement st = con.createStatement();
              ResultSet rs = st.executeQuery("select * from tyminterval3");
              ResultSetMetaData rsmd = rs.getMetaData();
              assertEquals(rsmd.getColumnType(1), Types.OTHER);
              assertEquals(rsmd.getColumnTypeName(1), "dsinterval");
              assertEquals(rsmd.getColumnClassName(1), "com.kingbase8.jdbc.DSInterval");
              assertEquals(rsmd.getColumnLabel(1), "t1");
              assertEquals(rsmd.getColumnName(1), "t1");
              assertEquals(rsmd.getColumnDisplaySize(1), 11);
              assertEquals(rsmd.getPrecision(1), 2);
              assertEquals(rsmd.getScale(1), 6);
              assertTrue(rs.next());
              assertEquals("12 12:12:12.111111", rs.getString(1));
              assertEquals("12 12:12:12.111111", rs.getObject(1).toString());
              assertEquals("class com.kingbase8.jdbc.DSInterval", rs.getObject(1).getClass().toString());
              assertTrue(rs.next());
              assertEquals("-12 12:12:12.111111", rs.getString(1));
              assertEquals("-12 12:12:12.111111", rs.getObject(1).toString());
              assertTrue(rs.next());
              assertEquals("12 12:12:12.111111", rs.getString(1));
              assertEquals("12 12:12:12.111111", rs.getObject(1).toString());
              rs.close();
              ps.close();
              st.close();
              stmt.close();
          }
      }


RowId 示例
----------

.. container:: EXAMPLE

   **例 12-19 RowId的使用示例**
  
   .. code::

     public void testRowId() throws SQLException {
       Properties properties = new Properties();
       properties.setProperty("rowidType", "rowid");
       Connection conn = TestUtils.openDB_(properties);
       Statement statement = conn.createStatement();
       String type = "tid";
       if (isDatabaseSupportRowid()) {
         statement.execute("set default_with_rowid=on;");
         type = "rowid";
       }
       ResultSet resultSet3 = statement.executeQuery("select rowid,1 from testrowidfrom");
       resultSet3.next();
       PreparedStatement preparedStatement = conn.prepareStatement("insert into testrowid values(?,?)");
       RowId rowId = resultSet3.getRowId(1);
       preparedStatement.setRowId(1, rowId);
       preparedStatement.setInt(2, resultSet3.getInt(2));
       preparedStatement.execute();

       DatabaseMetaData databaseMetaData = conn.getMetaData();
       if (isDatabaseSupportRowid()) {
         JunitUtils.astEqualsT(RowIdLifetime.ROWID_VALID_FOREVER, databaseMetaData.getRowIdLifetime());
       } else {
         JunitUtils.astEqualsT(RowIdLifetime.ROWID_VALID_TRANSACTION, databaseMetaData.getRowIdLifetime());
       }
       ResultSet rs2 = databaseMetaData.getColumns(null, null, "testrowid", "%");
       rs2.next();
       JunitUtils.astEqualsT("t1", rs2.getString(4));
       JunitUtils.astEqualsT(Types.ROWID, rs2.getInt(5));
       JunitUtils.astEqualsT(type, rs2.getString(6));
       ResultSet resultSet = statement.executeQuery("select * from testrowid");
       ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
       JunitUtils.astEqualsT("t1", resultSetMetaData.getColumnLabel(1));
       JunitUtils.astEqualsT(Types.ROWID, resultSetMetaData.getColumnType(1));
       JunitUtils.astEqualsT(type, resultSetMetaData.getColumnTypeName(1));
       while(resultSet.next()) {
         JunitUtils.astEqualsT(com.kingbase8.jdbc.KbRowId.class, resultSet.getObject(1).getClass());
         JunitUtils.astEqualsT(rowId.toString(), resultSet.getRowId(1).toString());
         //#if mvn.project.property.kingbase8.jdbc.spec >= "JDBC4.1"
         JunitUtils.astEqualsT(rowId.toString(), resultSet.getObject(1, RowId.class).toString());
         //#endif
         JunitUtils.astEqualsT(Arrays.toString(rowId.getBytes()), Arrays.toString(resultSet.getRowId(1).getBytes()));
         JunitUtils.astNotEqualsT(rowId.hashCode(), resultSet.getRowId(1).hashCode());
         if (isDatabaseSupportRowid()) {
           JunitUtils.astTrueT(resultSet.getRowId(1).equals(rowId));
         } else {
           JunitUtils.astFalseT(resultSet.getRowId(1).equals(rowId));
         }
       }
       conn.close();
     }

