zoukankan      html  css  js  c++  java
  • 【java】关于Statement和ResultSet

    今天写程序发现一个问题,错误示范如下:

    public static void main(String[] args) {
            // TODO Auto-generated method stub
            String driverName = "oracle.jdbc.driver.OracleDriver";
            String url = "jdbc:oracle:thin:@192.168.115.117:1521:ggg";
            String user = "admin";
            String pwd = "123";
            Connection con=null;
            ResultSet rs1,rs2;
            Statement stm;
            try {
                Class.forName(driverName).newInstance();
                con = DriverManager.getConnection(url, user, pwd);
                stm=con.createStatement();
                rs1=stm.executeQuery("select id from table1");
                rs2=stm.executeQuery("select id from table2");//执行此句时就把rs1给关闭了
                while(rs1.next()){ //调试可知,rs1.closed=true,此时执行next()返回false
                    System.out.println(rs1.getString("id"));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    //输入为空,如果把“rs2=.................”这句注释掉,则可以出现结果。

    先看看JDK API里面是怎么说的:

    public interface Statement

    The object used for executing a static SQL statement and returning the results it produces.

    By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

    “在默认情况下,同一时间每个 Statement 对象在只能打开一个 ResultSet 对象。因此,如果读取一个 ResultSet 对象与读取另一个交叉,则这两个对象必须是由不同的 Statement 对象生成的。如果存在某个语句的打开的当前 ResultSet 对象,则 Statement 接口中的所有执行方法都会隐式关闭它。”

    笔者注:“在默认情况下……”,不知道如何设置非默认情况下……:-)

    补充一下:

    public ResultSet executeQuery(String sql)
                           throws SQLException

    Returns:a ResultSet object that contains the data produced by the given query; never null即它的返回值永远不会为null。

    看来,以后得多看看JDK API帮助文档啊……呵呵,受益匪浅

  • 相关阅读:
    php 修改、增加xml结点属性的实现代码
    mysql rand随机查询记录效率
    分享:mysql 随机查询数据
    分享:perl 文件操作总结
    分享:Perl打开与读取文件的方法
    js日期相关函数总结分享
    php后台如何避免用户直接进入方法实例
    python 函数的进阶
    python 初识函数
    python 冒泡排序
  • 原文地址:https://www.cnblogs.com/gaojing/p/1328706.html
Copyright © 2011-2022 走看看