Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //STEP 1. Import required packages
- import java.sql.*;
- public class jdbcMinimums {
- // JDBC driver name and database URL
- static final String DB_URL = "jdbc:postgresql://localhost/postgres";
- // Database credentials
- static final String USER = "postgres";
- static final String PASS = "admin";
- public static void main(String[] args) {
- Connection conn = null;
- Statement stmt = null;
- try{
- //STEP 2: Register JDBC driver
- Class.forName("org.postgresql.Driver");
- //STEP 3: Open a connection
- System.out.println("Connecting to database...");
- conn = DriverManager.getConnection(DB_URL,USER,PASS);
- //STEP 4: Execute a query
- System.out.println("Creating statement...");
- stmt = conn.createStatement();
- String sql;
- sql = "SELECT full_name, address FROM customers";
- ResultSet rs = stmt.executeQuery(sql);
- //STEP 5: Extract data from result set
- while(rs.next()){
- //Retrieve by column name
- String fullName = rs.getString("full_name");
- String address = rs.getString("address");
- //Display values
- System.out.println(fullName + " " + address);
- }
- //STEP 6: Clean-up environment
- rs.close();
- stmt.close();
- conn.close();
- } catch (Exception e) {e.printStackTrace();}
- }//end main
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement