Java JDBC Select Multiple Records from table as List using PreparedStatement


Database Table Records:
Java JDBC Select records as List Example
Java code example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JDBCSelectAsListExample {
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
        String url ="jdbc:mysql://localhost:3306/my_uat";
        String userName="root";
        String password ="root123";
        String selectQuery ="Select data from my_table";
        Connection connection = DriverManager.getConnection(url,userName,password);
        PreparedStatement preparedStatement = connection.prepareStatement(selectQuery);
    
        List<String> dataList = new ArrayList<>();
        ResultSet resultSet = preparedStatement.executeQuery();
        
        //Converting resultSet to ArrayList
        while(resultSet.next()) {
            dataList.add(resultSet.getString(1));
        }

        //Print ArrayList
        System.out.println(dataList);
    
    }
}
Output:

[Europe, Asia, America]

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright Β© Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap