There are 5 steps to work with JDBC as illustrated with an example below:
- import java.sql.DriverManager;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.math.BigDecimal;
- import java.sql.Blob;
- public class JDBCConfiguration {
- public static void main(String[] args) {
- Connection con = null;
- Statement stmt = null;
- ResultSet rs = null;
- try {
- // 1. Load the driver
- Class.forName("com.mysql.jdbc.Driver");
- // 2. Get the DB connection via driver
- String dbURL = "jdbc:mysql://ishaan-pc:3306/mydb?user=root&password=root";
- con = DriverManager.getConnection(dbURL); // DriverManager : class
- // getConnection() : static
- // 3. Execute the SQL query via connection
- String query = "SELECT * FROM EMPLOYEE";
- stmt = con.createStatement();
- rs = stmt.executeQuery(query);
- // 4. Process the result
- while (rs.next()) {
- int id = rs.getInt("empid");
- String name = rs.getString("empname");
- long age = rs.getLong("age");
- double salary = rs.getDouble("salary");
- BigDecimal serialNumber = rs.getBigDecimal("serialnum");
- boolean status = rs.getBoolean("status");
- /*
- * BLOB - Binary Large Object that contains a variable amount of
- * data. Values are treated as binary strings.We don't need to
- * specify length while creating a column
- */
- Blob picture = rs.getBlob("emppicture");
- System.out.println("emp id: " + id);
- System.out.println("emp name: " + name);
- System.out.println("emp age: " + age);
- System.out.println("emp salary: " + salary);
- System.out.println("emp serial no: " + serialNumber);
- System.out.println("Is emp active?: " + status);
- System.out.println("emp photo: " + picture);
- }
- } catch (Exception e) {
- System.out.println("exception occured due to : " + e);
- } finally {
- // 5. Close all the JDBC objects
- try {
- if (con != null) {
- con.close();
- }
- if (stmt != null) {
- stmt.close();
- }
- if (rs != null) {
- rs.close();
- }
- } catch (Exception e) {
- System.out.println("exception occured in finally block : " + e);
- }
- }
- }
- }
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