Advertisement
hellom38

Example2 Java

Aug 17th, 2022
778
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. package Edureka;
  2. import java.sql.*;
  3. import java.sql.DriverManager;
  4. public class Example {
  5. // JDBC driver name and database URL
  6. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  7. static final String DB_URL = "jdbc:mysql://localhost/emp";
  8. //  Database credentials
  9. static final String USER = "root";
  10. static final String PASS = "";
  11. public static void main(String[] args) {
  12. Connection conn = null;
  13. Statement stmt = null;
  14. try{
  15. //STEP 2: Register JDBC driver
  16. Class.forName("com.mysql.cj.jdbc.Driver");
  17. //STEP 3: Open a connection
  18. System.out.println("Connecting to database...");
  19. conn = DriverManager.getConnection(DB_URL,"root","");
  20. //STEP 4: Execute a query
  21. System.out.println("Creating statement...");
  22. stmt = conn.createStatement();
  23. String sql;
  24. sql = "SELECT id, first, last, age FROM Employees";
  25. ResultSet rs = stmt.executeQuery(sql);
  26. //STEP 5: Extract data from result set
  27. while(rs.next()){
  28. //Retrieve by column name
  29. int id  = rs.getInt("id");
  30. int age = rs.getInt("age");
  31. String first = rs.getString("first");
  32. String last = rs.getString("last");
  33. //Display values
  34. System.out.print("ID: " + id);
  35. System.out.print(", Age: " + age);
  36. System.out.print(", First: " + first);
  37. System.out.println(", Last: " + last);
  38. }
  39. //STEP 6: Clean-up environment
  40. rs.close();
  41. stmt.close();
  42. conn.close();
  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. stmt.close()
  54. }catch(SQLException se2){
  55. }// nothing can be done
  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. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement