Java登陆第十天——JDBC(二)

发布时间 2023-11-20 19:42:28作者: ocraft

ResultSet接口常用方法

ResultSet存放的是DQL查询结果的结果集。常用方法如下:

方法 类型 描述
boolean next() throws SQLException 普通方法 指针移动到下一行(没有下一行返回false)
int getInt(String columnLabel) throws SQLException 普通方法 根据列名获取行
String getString(String columnLabel) throws SQLException 普通方法 根据列名获取行
int getInt(int columnIndex) throws SQLException 普通方法 获取第几列的行
String getString(int columnIndex) throws SQLException 普通方法 获取第几列的行

image
可以获取各种值,常用方法仅展示部分。

image

栗子:查询pon表

代码如下:

    public static void main(String[] args) {
        String user = "root";
        String password = "0000";

        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/UserTest?useSSL=false", user, password);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from pon");

            while (resultSet.next()) {
                String p_name = resultSet.getString("p_name");//获取p_name列的行
                String p_age = resultSet.getString("p_age");//获取p_age列的行

                System.out.println("姓名:"+p_name+",年龄:"+p_age);
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

程序运行结果:

姓名:李四,年龄:18
姓名:水杯,年龄:52

栗子:利用另一种方法查询pon表

代码如下:

public static void main(String[] args) {
        String user = "root";
        String password = "0000";

        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/UserTest?useSSL=false", user, password);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from pon");

            while (resultSet.next()) {
                String p_name = resultSet.getString(1);//第 1 列是p_name列,并获取行
                String p_age = resultSet.getString(2);//第 2 列是p_age列,并获取行

                System.out.println("姓名:"+p_name+",年龄:"+p_age);
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

程序运行结果:

姓名:李四,年龄:18
姓名:水杯,年龄:52

ResultSet的遍历其实类似于迭代器。

解析:
image