简体   繁体   中英

How to get all users from a table into an array or list and print it

I have to create an application using Java and JDBC in Eclipse IDE which stores user details in a MySQL database and is able to perform operations like insert, delete, display, etc.

I know how to display all user details without putting it in an ArrayList like below:

import java.sql.*;

public class JDBC {
    
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","root");
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from student");
        
        while(rs.next())
        {
            String name1 = rs.getString("name");
            int contact1 = rs.getInt("contact");
            int age1 = rs.getInt("age");
            
            System.out.println(name1 + " " + contact1 + " " + age1);
        }
        
        st.close();
        con.close();
    }
}

However, I am required to display user details after putting it in an array or ArrayList. I don't know how to put it in an array or ArrayList and then print it.

As Slaw already pointed out, create a class that is able to store one row from the database, iterate over the result set and add a new instance to a list for each row read. Close the connection, iterate over your list and dump the objects to standard output.

Assuming you are using Java 14 or higher, it would be even easier to create a record for that (basically a class with only final fields and getters and an all arguments constructor, that the compiler generates for you). The following code is based on yours with minimal changes to adopt the idea outlined in the first paragraph.

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

public class JDCB {
  record Student(String name, int contact, int age) {
    // might want to override toString() to make it prettier on console
  }

  public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.cj.jdbc.Driver");

    Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","root");
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery("select * from student");

    final List<Student> students = new LinkedList<>(); // better suited for adding elements one by one than ArrayList<>

    while(rs.next()) {
      students.add(new Student(
          rs.getString("name"),
          rs.getInt("contact"),
          rs.getInt("age")
      ));
    }

    st.close();
    con.close();

    students.forEach(System.out::println);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM