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!

Top Hashtags:

Advertisements

Advertisements




Advertisements