Java Database Connectivity


JDBC (Java Database Connectivity) is a standard API for accessing and manipulating relational databases from Java programs. It provides a set of interfaces and classes that enable Java programs to interact with databases such as MySQL, Oracle, SQL Server, etc.

JDBC is designed around the concept of a driver, which is a software component that allows Java programs to communicate with a specific type of database. Each driver implements the JDBC API for a specific database vendor and can be loaded dynamically at runtime.

Here is an example of using JDBC to connect to a MySQL database and execute a simple query:

import java.sql.*;

public class JdbcExample {
   public static void main(String[] args) {
      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;

      try {
         // Load the MySQL JDBC driver
         Class.forName("com.mysql.jdbc.Driver");

         // Connect to the database
         conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");

         // Create a statement object
         stmt = conn.createStatement();

         // Execute a query
         rs = stmt.executeQuery("SELECT * FROM mytable");

         // Process the results
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            double salary = rs.getDouble("salary");
            System.out.println("id=" + id + ", name=" + name + ", salary=" + salary);
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      } finally {
         // Close the result set, statement, and connection objects
         try { rs.close(); } catch (Exception e) { }
         try { stmt.close(); } catch (Exception e) { }
         try { conn.close(); } catch (Exception e) { }
      }
   }
}

In this example, we first load the MySQL JDBC driver using the Class.forName() method. We then establish a connection to the database using the DriverManager.getConnection() method. Once we have a connection, we create a statement object using the Connection.createStatement() method, and execute a query using the Statement.executeQuery() method. Finally, we process the results using the ResultSet object returned by the query.

Note that we also have to handle exceptions and close the result set, statement, and connection objects in a finally block to ensure proper cleanup.

JDBC provides many other features for more advanced database operations, such as prepared statements, batch updates, and transaction management.

A quick recap of java