JDBC----学习(5)--通过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 当然也需要进行关闭.
     *
     * @throws Exception
     */
    @Test
    public void testResultSet() throws Exception {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            String sql = "select CUSTOMER_ID ,CUSTOMER_NAME from CUSTOMERS";
            connection = JDBCTools.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                System.out.println(id);
                System.out.println(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JDBCTools.colse(statement, connection, resultSet);
        }

    }

猜你喜欢

转载自blog.csdn.net/lsh15846393847/article/details/89187449
今日推荐