ResultSet

public static void main(String[] args) throws Exception{
       dim();
   }
   public static void dim() throws Exception{
       String url = "jdbc:mysql:///xuexi";
       String user = "root";
       String passwd = "123321";
       Connection connection = DriverManager.getConnection(url, user, passwd);
       String sql = "SELECT * from yg";
       Statement statement = connection.createStatement();
       ResultSet resultSet = statement.executeQuery(sql);
       //处理结果,遍历查询到的所有数据
       while (resultSet.next()){   //光标向下一行,并判断这一行是否有数据
           //获取数据
           System.out.println(resultSet.getInt(1));
           System.out.println(resultSet.getString(2));
           System.out.println(resultSet.getString(3));
           System.out.println(resultSet.getDate(4));
           System.out.println(resultSet.getInt(5));
           System.out.println("---------------------");
       }
       resultSet.close();
       connection.close();
       statement.close();

一行数据就对应着一行数据

将表中的数据封装进对象存入ArrayList集合中

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
public class Demo04 {
    static class  dim{
            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            private int id;
            private String name;

            @Override
            public String toString() {
                return "Demo05_Account{" +
                        "id=" + id +
                        ", name='" + name + '\'' +
                        '}';
            }

    }
    public static void main(String[] args) throws Exception{
        String url = "jdbc:mysql:///xuexi";
        String user = "root";
        String passwd = "123321";
        Connection connection = DriverManager.getConnection(url,user,passwd);
        Statement statement = connection.createStatement();

        String sql = "SELECT * from bm";
        ResultSet resultSet = statement.executeQuery(sql);
        ArrayList<dim> list = new ArrayList<>();
        while (resultSet.next()){
            dim d1 = new dim();
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            d1.setId(id);
            d1.setName(name);
            list.add(d1);
        }
        System.out.println(list.toString());

    }
}

您可能还喜欢...