Java code for connecting Mysql database and using Arraylist type

To get to use JDBC and ArrayList I make the following example to help myself.  The following is the steps:

  • Create a database "travel" with a table named "person"
  • Define a class named "Person" for mapping the person table's columns
  • Connecting Mysql database
  • Select some records from the database "travel"
  • Make objects based on each record extracted from  "person" table
  • Using ArrayList of object to store the objects of Person.
  • Print the data in ArrayList

The following is the code:

 * To change this template, choose Tools | Templates
 * and open the template in the editor.
package javaapplication1;
 * @author wongwong
public class Person {
    private String name;
    private String jobtitle;
    private int frequentflyer;
    public int getFrequentflyer() {
        return frequentflyer;
    public void setFrequentflyer(int frequentflyer) {
        this.frequentflyer = frequentflyer;
    public String getJobtitle() {
        return jobtitle;
    public void setJobtitle(String jobtitle) {
        this.jobtitle = jobtitle;
    public String getName() {
        return name;
    public void setName(String name) { = name;

package javaapplication1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javaapplication1.Person;
public class Main {
    public static void main(String[] args) throws SQLException {
        ArrayList<Person> personlist = new ArrayList<Person>();
        //List<Person> personlist = new List<Person>();
        try {
            // Step 1: Load the JDBC driver. jdbc:mysql://localhost:3306/travel
            // Step 2: Establish the connection to the database.
            String url = "jdbc:mysql://localhost:3306/travel";
            Connection conn = DriverManager.getConnection(url, "root", "admin");
            Statement st = conn.createStatement();
            ResultSet srs = st.executeQuery("SELECT * FROM person");
            while ( {
                Person person = new Person();
        } catch (Exception e) {
            System.err.println("Got an exception! ");
Category >> Database  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Vila Rica

    Hey wongwong!!
    good job simple and efficient, thart’s the way that I like.


  • Jez Shanes

    thanks you so much!!

  • Ende

    Dear Sir
    In your introduction you mentioned this:

    Using ArrayList of object to store the objects of Person.

    However, your code does not reflect this. Why?