Java_jdbc 基础笔记之五 数据库连接 (ResultSet)

/**
 * ResultSet: 结果集. 封装了使用 JDBC 进行查询的结果. 
 * 1. 调用 Statement 对象的 executeQuery(sql)可以得到结果集.
 * 2. ResultSet 返回的实际上就是一张数据表. 有一个指针指向数据表的第一行的前面. 
 * 可以调用 next()方法检测下一行是否有效. 若有效该方法返回 true, 且指针下移. 
 * 相当于 Iterator 对象的 hasNext() 和 next()方法的结合体
 * 3. 当指针对位到一行时, 可以通过调用 getXxx(index) 或 getXxx(columnName) 获取每一列的值.
 * 例如: getInt(1), getString("name") 4. ResultSet 当然也需要进行关闭.

 */
@Test
    public void testResultSet(){
        //1获取Connection
        Connection conn=null;
        Statement statement=null;
        ResultSet rs=null;
        try {
            conn=jdbc.JDBCTools.getConnection();
            //2 获取Statement
            statement=conn.createStatement();
            //3、准备SQL
            String sql="select id,name,email,birth from customers where id=8";
            //4执行查询,得到Statement
            rs=statement.executeQuery(sql);
            //5 处理ResultSet
            while(rs.next()){
                int id=rs.getInt(1);
                String name=rs.getString(2);
                String email=rs.getString(3);
                Date birth=rs.getDate(4);
                System.out.println(id);
                System.out.println(name);
                System.out.println(email);
                System.out.println(birth);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            jdbc.JDBCTools.close(rs, statement, conn);
        }

    }

转: https://blog.csdn.net/YL1214012127/article/details/48273693

猜你喜欢

转载自www.cnblogs.com/fps2tao/p/12023630.html