JDBC Statement example to Select list of Records from database
Here is an example to show you how to select the entire records from table via JDBC statement, and display all the records via a ResultSet object.
To issue a select query, calls the Statement.executeQuery method like this:
String selectTableSQL = "SELECT USER_ID, USERNAME from EMPLOYEE"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(selectTableQuery); while (rs.next()) { String userid = rs.getString("USER_ID"); String username = rs.getString("USERNAME"); }
Full example…
File: JDBCStatementSelectExample.java
package com.simplecode.jdbc; import java.sql.DriverManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCStatementSelectExample { 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 { selectRecordsFromEmployeeTable(); } catch (SQLException e) { System.err.println(e.getMessage()); } } private static void selectRecordsFromEmployeeTable() throws SQLException { Connection dbConnection = null; Statement statement = null; String selectTableQuery = "SELECT USER_ID, USERNAME from EMPLOYEE"; try { dbConnection = getDBConnection(); statement = dbConnection.createStatement(); System.out.println(selectTableQuery); // execute select SQL statement ResultSet rs = statement.executeQuery(selectTableQuery); 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 (statement != null) { statement.close(); } if (dbConnection != null) { dbConnection.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(e.getMessage()); } return dbConnection; } }
|