Sunday, April 29, 2018

What are the necessary steps to work with JDBC ?

There are 5 steps to work with JDBC as illustrated with an example below:
  1. import java.sql.DriverManager;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.Statement;
  5. import java.math.BigDecimal;
  6. import java.sql.Blob;

  7. public class JDBCConfiguration {

  8. public static void main(String[] args) {

  9. Connection con = null;
  10. Statement stmt = null;
  11. ResultSet rs = null;
  12. try {

  13. // 1. Load the driver
  14. Class.forName("com.mysql.jdbc.Driver");

  15. // 2. Get the DB connection via driver
  16. String dbURL = "jdbc:mysql://ishaan-pc:3306/mydb?user=root&password=root";
  17. con = DriverManager.getConnection(dbURL); // DriverManager : class
  18. // getConnection() : static

  19. // 3. Execute the SQL query via connection
  20. String query = "SELECT * FROM EMPLOYEE";
  21. stmt = con.createStatement();
  22. rs = stmt.executeQuery(query);

  23. // 4. Process the result
  24. while (rs.next()) {
  25. int id = rs.getInt("empid");
  26. String name = rs.getString("empname");
  27. long age = rs.getLong("age");
  28. double salary = rs.getDouble("salary");
  29. BigDecimal serialNumber = rs.getBigDecimal("serialnum");
  30. boolean status = rs.getBoolean("status");
  31. /*
  32. * BLOB - Binary Large Object that contains a variable amount of
  33. * data. Values are treated as binary strings.We don't need to
  34. * specify length while creating a column
  35. */
  36. Blob picture = rs.getBlob("emppicture");

  37. System.out.println("emp id: " + id);
  38. System.out.println("emp name: " + name);
  39. System.out.println("emp age: " + age);
  40. System.out.println("emp salary: " + salary);
  41. System.out.println("emp serial no: " + serialNumber);
  42. System.out.println("Is emp active?: " + status);
  43. System.out.println("emp photo: " + picture);

  44. }
  45. } catch (Exception e) {
  46. System.out.println("exception occured due to : " + e);
  47. } finally {

  48. // 5. Close all the JDBC objects
  49. try {
  50. if (con != null) {
  51. con.close();
  52. }
  53. if (stmt != null) {
  54. stmt.close();
  55. }
  56. if (rs != null) {
  57. rs.close();
  58. }
  59. } catch (Exception e) {
  60. System.out.println("exception occured in finally block : " + e);
  61. }
  62. }
  63. }
  64. }
Output: 
emp id: 101
emp name: ishaan
emp age: 21
emp salary: 9000
emp serial no: 11229933994439101
Is emp active?: true
emp photo: 👨

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...