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]



Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.