Java Tutorial/Database/JDBC Driver

Материал из Java эксперт
Перейти к: навигация, поиск

Loading a JDBC Driver: Using Class.forName()

String className = "org.gjt.mm.mysql.Driver";
Class driverObject = Class.forName(className);





To test a JDBC driver installation using MySQL

public class MainClass {
  public static void main(String[] args) {
    try {
      String className = "org.gjt.mm.mysql.Driver";
      Class driverObject = Class.forName(className);
      System.out.println("driverObject=" + driverObject);
      System.out.println("your installation of JDBC Driver OK.");
    } catch (Exception e) {
      System.out.println("Failed: JDBC Driver Error: " + e.getMessage());
    }
  }
}





To test a JDBC driver installation using Oracle

public class MainClass {
  public static void main(String[] args) {
    try {
      String className = "oracle.jdbc.driver.OracleDriver";
      Class driverObject = Class.forName(className);
      System.out.println("driverObject=" + driverObject);
      System.out.println("your installation of JDBC Driver OK.");
    }
    catch (Exception e) {
      System.out.println("Failed: JDBC Driver Error: " + e.getMessage());
    }
  }
}





Using DriverManager.registerDriver()

//String className = "org.gjt.mm.mysql.Driver";
try {
   // Registers the given driver with the DriverManager.
   DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
   // here the class is loaded
}
catch (SQLException e) {
   e.printStackTrace();
}





What is a JDBC Driver?

  1. A JDBC driver allows a Java application/client to communicate with a SQL database.
  2. A JDBC driver is a Java class that implements the JDBC"s java.sql.Driver interface.
  3. A JDBC driver converts program (and typically SQL) requests for a particular database.


What is JDBC?

JDBC is a set of programming APIs that allows easy connection to a wide range of databases (especially relational databases) through Java programs. (JDBC Recipes: A Problem-Solution Approach by Mahmoud Parsian Apress 2005)

The following are core JDBC classes, interfaces, and exceptions in the java.sql package:

  1. DriverManager
  2. Connection
  3. Statement
  4. PreparedStatement
  5. CallableStatement
  6. ResultSet
  7. SQLException