- Java Guides
- Technologies used
- Download PostgreSQL JDBC Driver
- PostgreSQL Database Setup
- JDBC PostgreSQL Select Single Record Example
- Java JDBC: A SQL SELECT query example
- JDBC SELECT query: A sample database
- How to perform a JDBC SELECT query against a database
- Creating a valid SQL SELECT query
- Reading the JDBC SELECT query results (i.e., a Java JDBC ResultSet)
- Our JDBC SELECT query example program — Query1.java
- Download our example JDBC select program
- Conclusion
- Related JDBC content
- JDBC Select All Records Example
- JDBC Select All Records Example
Java Guides
In this previous tutorial, we have seen how to insert one or multiple rows into the PostgreSQL database using the JDBC API. In this tutorial, you will learn how to query data from a table in the PostgreSQL database using the JDBC API.
- Establish a database connection to the PostgreSQL server.
- Create an instance of the Statement object
- Execute a statement to get a ResultSet object
- Process the ResultSet object.
- Close the database connection.
Technologies used
Download PostgreSQL JDBC Driver
To connect to the PostgreSQL database server from a Java program, you need to have a PostgreSQL JDBC driver. You can download the latest version of the driver on the postgresql.org website via the download page.
https://mvnrepository.com/artifact/org.postgresql/postgresql --> dependency> groupId>org.postgresqlgroupId> artifactId>postgresqlartifactId> version>42.2.9version> dependency>
// https://mvnrepository.com/artifact/org.postgresql/postgresql compile group: 'org.postgresql', name: 'postgresql', version: '42.2.9'
PostgreSQL Database Setup
JDBC PostgreSQL Select Single Record Example
package net.javaguides.postgresql.tutorial; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * Select PreparedStatement JDBC Example * * @author Ramesh Fadatare * */ public class RetrieveRecordsExample < private final static String url = "jdbc:postgresql://localhost/mydb"; private final static String user = "postgres"; private final static String password = "root"; private static final String QUERY = "select id,name,email,country,password from Users where style="box-sizing: border-box;">"; private static final String SELECT_ALL_QUERY = "select * from users"; public void getUserById() < // using try-with-resources to avoid closing resources (boiler plate // code) // Step 1: Establishing a Connection try (Connection connection = DriverManager.getConnection(url, user, password); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(QUERY);) < preparedStatement.setInt(1, 1); System.out.println(preparedStatement); // Step 3: Execute the query or update query ResultSet rs = preparedStatement.executeQuery(); // Step 4: Process the ResultSet object. while (rs.next()) < int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String country = rs.getString("country"); String password = rs.getString("password"); System.out.println(id + "," + name + "," + email + "," + country + "," + password); > > catch (SQLException e) < printSQLException(e); >> public void getAllUsers() < // using try-with-resources to avoid closing resources (boiler plate // code) // Step 1: Establishing a Connection try (Connection connection = DriverManager.getConnection(url, user, password); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_QUERY);) < System.out.println(preparedStatement); // Step 3: Execute the query or update query ResultSet rs = preparedStatement.executeQuery(); // Step 4: Process the ResultSet object. while (rs.next()) < int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String country = rs.getString("country"); String password = rs.getString("password"); System.out.println(id + "," + name + "," + email + "," + country + "," + password); > > catch (SQLException e) < printSQLException(e); >> public static void main(String[] args) < RetrieveRecordsExample example = new RetrieveRecordsExample(); example.getUserById(); example.getAllUsers(); > public static void printSQLException(SQLException ex) < for (Throwable e: ex) < if (e instanceof SQLException) < e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) < System.out.println("Cause: " + t); t = t.getCause(); > > > > >
select id,name,email,country,password from Users where * from users 2,Ramesh,ramesh@gmail.com,India,password123 3,John,john@gmail.com,US,password123
In this tutorial, we have shown you how to query data from the PostgreSQL database using the JDBC API.
Java JDBC: A SQL SELECT query example
Java JDBC FAQ: Can you share an example of a SQL SELECT query using the standard JDBC syntax?
In my JDBC connection article I showed how to connect your Java applications to standard SQL databases like MySQL, SQL Server, Oracle, SQLite, and others using JDBC. In those examples I showed how to connect to two different databases so you could see how little the code changes when you switch from one database to another.
In this SELECT query tutorial I’ll take JDBC to the next step, showing how to create and execute a SQL SELECT statement in your Java code.
JDBC SELECT query: A sample database
Before looking at the SQL queries, let’s take a quick look at our sample database.
In all of these examples I’ll access a database named «Demo», and in these SELECT query examples I’ll access a database table named «Customers» that’s contained in the Demo database.
Here’s what the Customers table looks like:
Cnum | Lname | Salutation | City | Snum |
---|---|---|---|---|
1001 | Simpson | Mr. | Springfield | 2001 |
1002 | MacBeal | Ms. | Boston | 2004 |
1003 | Flinstone | Mr. | Bedrock | 2003 |
1004 | Cramden | Mr. | New York | 2001 |
As you can see, the Customers table contains these four sample records. (I populated that data in my JDBC SQL INSERT tutorial.)
How to perform a JDBC SELECT query against a database
Querying a SQL database with JDBC is typically a three-step process:
- Create a JDBC ResultSet object.
- Execute the SQL SELECT query you want to run.
- Read the results.
The hardest part of the process is defining the query you want to run, and then writing the code to read and manipulate the results of your SELECT query.
Creating a valid SQL SELECT query
To demontrate this I’ll write this simple SQL SELECT query:
SELECT Lname FROM Customers WHERE Snum = 2001;
This statement returns each Lname (last name) record from the Customers database, where Snum (salesperson id-number) equals 2001. In plain English, you might say «give me the last name of every customer where the salesperson id-number is 2001».
Now that we know the information we want to retrieve, how do we put this SQL statement into a Java program? It’s actually very simple. Here’s the JDBC code necessary to create and execute this query:
Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
In the first step, I create a Java Statement objection from the Connection object. That’s really just an intermediate step that lets us do what we want to do in the next step: Execute our query, and get a ResultSet object. The ResultSet object rs now contains the results from the database query. Now we can work with those results.
Reading the JDBC SELECT query results (i.e., a Java JDBC ResultSet)
After you execute the SQL query, how do you read the results? Well, JDBC makes this pretty easy also. In many cases, you can just use the next() method of the ResultSet object. After the previous two lines, you might add a loop like this to read the results:
This loop reads the last name returned in each record, and prints it to the screen using the normal System.out.println() method. In the case of our sample database, the printed results look like this:
because these are the last names of the two customer records where Snum equals 2001.
Notice that in this example all we’re doing is printing our results. In many JDBC applications, you’ll probably want to do something else with the results, such as displaying them in a table or grid in a GUI applet or application.
Our JDBC SELECT query example program — Query1.java
The full source code for our example JDBC program (Query1.java) is shown in Listing 1.
// Query1.java: Query an mSQL database using JDBC. import java.sql.*; /** * A JDBC SELECT (JDBC query) example program. */ class Query1 < public static void main (String[] args) < try < String url = "jdbc:msql://200.210.220.1:1114/Demo"; Connection conn = DriverManager.getConnection(url,"",""); Statement stmt = conn.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001"); while ( rs.next() ) < String lastName = rs.getString("Lname"); System.out.println(lastName); >conn.close(); > catch (Exception e) < System.err.println("Got an exception! "); System.err.println(e.getMessage()); >> >
The source code for the Query1.java program shows how to query an SQL database for the information you want, using Java JDBC methods.
Download our example JDBC select program
If you’re interested, you can download the Java source code for our Query1.java program. You can test this JDBC example code on your own system, but note that you’ll need to change the lines where we create our url and conn objects to reflect your own database configuration.
Conclusion
Querying an SQL database with JDBC is a simple three step process, once you know how to do it. Just (1) create a ResultSet object, (2) execute the query, and then (3) read the results.
Related JDBC content
Please note that there is a *lot* of newer Java and JDBC content on my blog, including these JDBC tips:
- How do I connect to a database?
- How do I create and use a PreparedStatement?
- A good example of using try/catch/finally with JDBC
- Using a PreparedStatement with a SELECT statement and LIKE clause
- Sample JDBC PreparedStatement (using SQL UPDATE)
- A sample Java/JDBC program to connect to a database
- The SQLProcessor as a JDBC Facade (a better way to use JDBC)
- A simple Spring JDBC example showing a SELECT and INSERT
- Spring JDBC SELECT statement examples
- Spring JDBC DELETE examples
- How to test your Spring JDBC code
JDBC Select All Records Example
In this tutorial we will learn how select all records from the table use mysql JDBC driver.
In this tutorial we will learn how select all records from the table use mysql JDBC driver.
JDBC Select All Records Example
In this tutorial we will learn how select all records from the table use mysql JDBC driver. This tutorial example for select all records from table if exist and defined how the records fetch and store.
This example applied mysql query «SELECT * FROM user» and applied the given step by step that describe in «SelectAllRecords.java» class and given steps as:
1.Import the packages
2.Register the JDBC driver
3.Open a connection
4.Execute a query
5.Extract Data
First we create connection to the database server, again create query and execute , store the result in ResultSet object and Extract data. While loop extract data from ResultSet rs one by one row and print also. The code of «SelectAllRecords.java» given below :
import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; import java.sql.SQLException; import java.sql.ResultSet; public class SelectAllRecords < // JDBC driver name and database URL static String driverName = "com.mysql.jdbc.Driver"; static String url = "jdbc:mysql://localhost:3306/"; // defined and set value in dbName, userName and password variables static String dbName = "testjdbc"; static String userName = "root"; static String password = ""; public static void main(String[] args)< // create Connection con, and Statement stmt Connection con=null; Statement stmt=null; try< Class.forName(driverName).newInstance(); con = DriverManager.getConnection(url+dbName, userName, password); try< stmt = con.createStatement(); String query = "SELECT * FROM user"; ResultSet rs=stmt.executeQuery(query); System.out.println("user_id"+"\t"+"user_name"); //Extact result from ResultSet rs while(rs.next())< System.out.println(""+rs.getInt("user_id")+"\t"+rs.getString("user_name")); >// close ResultSet rs rs.close(); > catch(SQLException s) < s.printStackTrace(); >// close Connection and Statement con.close(); stmt.close(); >catch (Exception e) < e.printStackTrace(); >> >
Program Output:
F:\jdbc>java SelectAllRecords
user_id user_name
1 User1
2 User2
3 User3
4 User4
5 User5