JDBC Tutorial Reading Notes

以下阅读笔记,整理源于以下原文,多谢分享,如有异议即删除:

What is JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below:

  • Making a connection to a database.
  • Creating SQL or MySQL statements.
  • Executing SQL or MySQL queries in the database.
  • Viewing & Modifying the resulting records.

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers :

  • JDBC API: This provides the application-to-JDBC Manager connection.
    The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.
  • JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
    The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases

Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application:
在这里插入图片描述

Common JDBC Components

The JDBC API provides the following interfaces and classes:

  • DriverManager (manages a list of database drivers, matche drivers)
    This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

  • Driver (handles the communications with the database server)
    You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.

  • Connection(with all methods for contacting a database)
    The connection object represents communication context, i.e., all communication with database is through connection object only.

  • Statement.
    You use objects created from this interface to submit the SQL statements to the database

  • ResultSet.
    These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.

  • SQLException.
    This class handles any errors that occur in a database application.

JDBC - Sample, Example Code

This chapter provides an example of how to create a simple JDBC application. This will show you how to open a database connection, execute a SQL query, and display the results。

Creating JDBC Application

There are following six steps involved in building a JDBC application:

  • Import the packages.
    Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.

  • Register the JDBC driver.
    initialize a driver so you can open a communication channel with the database.

  • Open a connection
    Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.

  • Execute a query
    Requires using an object of type Statement for building and submitting an SQL statement to the database.

  • Extract data from result set.
    Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.

  • Clean up the environment.
    Requires explicitly closing all database resources versus relying on the JVM’s garbage collection.

Sample Code

//STEP 1. Import required packages
import java.sql.*;

public class FirstExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end FirstExample

Now let us compile the above example as follows:

javac FirstExample.java

JDBC - Driver Types

What is JDBC Driver?

JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server.using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK, contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers.

JDBC Drivers Types

JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories:

  • Type 1: JDBC-ODBC Bridge Driver.
    In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database.When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
    在这里插入图片描述

待续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值