JDBC PreparedStatement example to Select list of the records
In this example let us learn how to select records from table via JDBC PreparedStatement, and display the records via a ResultSet object.
To issue a select query, call the PreparedStatement.executeQuery() method like this :
String selectQuery = "SELECT USER_ID, USERNAME FROM EMPLOYEE WHERE USER_ID = ?";
PreparedStatement preparedStatement = connection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1000);
ResultSet rs = preparedStatement.executeQuery(selectQuery);
while (rs.next())
{
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
String createdBy = rs.getString("CREATED_BY");
}
Full example…
package com.simplecode.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCPreparedStmtSelectExample
{
private static final String dbDriver = "oracle.jdbc.driver.OracleDriver";
private static String serverName = "127.0.0.1";
private static String portNumber = "1521";
private static String sid = "XE";
private static final String dbUrl = "jdbc:oracle:thin:@" + serverName + ":"
+ portNumber + ":" + sid;
private static final String dbUser = "system";
private static final String dbPassword = "admin";
public static void main(String[] argc)
{
try
{
selectRecordsFromTable();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
private static void selectRecordsFromTable() throws SQLException
{
Connection connection = null;
PreparedStatement prepareStmt = null;
String selectQuery = "SELECT USER_ID, USERNAME FROM EMPLOYEE WHERE USER_ID = ?";
try
{
connection = getDBConnection();
prepareStmt = connection.prepareStatement(selectQuery);
prepareStmt.setInt(1, 1001);
// execute select SQL stetement
ResultSet rs = prepareStmt.executeQuery();
while (rs.next())
{
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
System.out.println("userid : " + userid);
System.out.println("username : " + username);
}
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
finally
{
if (prepareStmt != null)
{
prepareStmt.close();
}
if (connection != null)
{
connection.close();
}
}
}
private static Connection getDBConnection()
{
Connection dbConnection = null;
try
{
Class.forName(dbDriver);
}
catch (ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
try
{
dbConnection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
return dbConnection;
}
catch (SQLException e)
{
System.err.println("Db "+e.getMessage());
}
return dbConnection;
}
}
