boldercoder
boldercoder

Reputation: 49

Way to store MySQL data into java objects

I'm working on a project where I would need to write a program to take in data from MySql into a java program then save that data into an object to be used later. I already managed to set up the JDBC connection to the MySql database and get all the information from the database as well as being able to write queries to the DB. What I want to do now is store that information into an object. So, I created a table called people with the columns name and age that contain information. In my program, I have a people class with the name and age fields shown below

public class People {
private String name;
private int age;


public people(String name, int age) {
    this.name = name;
    this.age =age;
}

public String getName() {
    return name;
}

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

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

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

}

I'm wondering how I could take the MySQL data that I imported and using this people class create objects from it?

Upvotes: 0

Views: 2083

Answers (2)

Twistleton
Twistleton

Reputation: 2935

A very primitive solution could look like this:

    String sql  = " select name         " +
                  "      , age          " +               
                  "   from TABLE_PEOPLE ";
    
    ArrayList<People> staffs = new ArrayList<>();

    try {
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            People people = new People(resultSet.getString("name"),
                                       resultSet.getInt("age"));
            staffs.add(people);
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();

An important note: Your constructor is wrong. A constructor starts with a capital letter.

 public People(String name, int age) {
    this.name = name;
    this.age = age;
 }

Upvotes: 2

Kyrillus K
Kyrillus K

Reputation: 35

You should map your Person class with the @Entity to your db table(https://www.baeldung.com/jpa-entity-table-names) and create a TypedQuery(https://www.objectdb.com/java/jpa/query/api) and select all entries in the Database. Or you could just create a normal Query and parse the resultList to a list of peoples.

Upvotes: 3

Related Questions