Advertisement
Guest User

aswdadwadwa

a guest
Jun 26th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. //STEP 1. Import required packages
  2. import java.sql.*;
  3.  
  4. public class DBConnect {
  5. // JDBC driver name and database URL
  6. static final String JDBC_DRIVER = "org.postgresql.Driver";
  7. static final String DB_URL = "jdbc:postgresql://localhost:5432/postgres";
  8.  
  9. // Database credentials
  10. static final String USER = "postgres";
  11. static final String PASS = "postgres";
  12.  
  13. public static void main(String[] args) {
  14. Connection conn = null;
  15. Statement stmt = null;
  16. try{
  17. //STEP 2: Register JDBC driver
  18. Class.forName("org.postgresql.Driver");
  19.  
  20. //STEP 3: Open a connection
  21. System.out.println("Connecting to a selected database...");
  22. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  23. System.out.println("Connected database successfully...");
  24.  
  25. //STEP 4: Execute a query
  26. System.out.println("Inserting records into the table...");
  27. stmt = conn.createStatement();
  28.  
  29. String sql = "INSERT INTO Registration " +
  30. "VALUES (100, 'Zara', 'Ali', 18)";
  31. stmt.executeUpdate(sql);
  32. sql = "INSERT INTO Registration " +
  33. "VALUES (101, 'Mahnaz', 'Fatma', 25)";
  34. stmt.executeUpdate(sql);
  35. sql = "INSERT INTO Registration " +
  36. "VALUES (102, 'Zaid', 'Khan', 30)";
  37. stmt.executeUpdate(sql);
  38. sql = "INSERT INTO Registration " +
  39. "VALUES(103, 'Sumit', 'Mittal', 28)";
  40. stmt.executeUpdate(sql);
  41. System.out.println("Inserted records into the table...");
  42.  
  43. }catch(SQLException se){
  44. //Handle errors for JDBC
  45. se.printStackTrace();
  46. }catch(Exception e){
  47. //Handle errors for Class.forName
  48. e.printStackTrace();
  49. }finally{
  50. //finally block used to close resources
  51. try{
  52. if(stmt!=null)
  53. conn.close();
  54. }catch(SQLException se){
  55. }// do nothing
  56. try{
  57. if(conn!=null)
  58. conn.close();
  59. }catch(SQLException se){
  60. se.printStackTrace();
  61. }//end finally try
  62. }//end try
  63. System.out.println("Goodbye!");
  64. }//end main
  65. }//end JDBCExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement