Advertisement
Guest User

Untitled

a guest
Sep 18th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. static final String JDBC_DRIVER = "org.postgresql.Driver";
  2. static final String DB_URL = "jdbc:postgresql://localhost:5432/user1";
  3.  
  4. // Database credentials
  5. static final String USER = "root";
  6. static final String PASS = "root";
  7.  
  8. public static void main(String[] args)
  9. {
  10. Connection conn = null;
  11. Statement st = null;
  12. try{
  13. //STEP 2: Register JDBC driver
  14. Class.forName("org.postgresql.Driver");
  15.  
  16. //STEP 3: Open a connection
  17. System.out.println("Connecting to database...");
  18. conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","root","root");
  19.  
  20. //STEP 4: Execute a query
  21. System.out.println("Creating statement...");
  22. st = conn.createStatement();
  23. String sql;
  24. sql = "SELECT first, last FROM Employees";
  25. ResultSet rs = st.executeQuery(sql);
  26.  
  27. //STEP 5: Extract data from result set
  28. while(rs.next()){
  29. //Retrieve by column name
  30. String first = rs.getString("first");
  31. String last = rs.getString("last");
  32.  
  33. //Display values
  34. System.out.print(", First: " + first);
  35. System.out.println(", Last: " + last);
  36. }
  37. //STEP 6: Clean-up environment
  38. rs.close();
  39. st.close();
  40. conn.close();
  41. }catch(SQLException se){
  42. //Handle errors for JDBC
  43. se.printStackTrace();
  44. }catch(Exception e){
  45. //Handle errors for Class.forName
  46. e.printStackTrace();
  47. }
  48. finally
  49. {
  50. //finally block used to close resources
  51. try{
  52. if(st!=null)
  53. st.close();
  54. }catch(SQLException se2){
  55. }// nothing we can do
  56. try{
  57. if(conn!=null)
  58. conn.close();
  59. }
  60. catch(SQLException se){
  61. se.printStackTrace();
  62. }//end finally try
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement