Java Tutorial/Database/JDBC Driver
Содержание
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?
- A JDBC driver allows a Java application/client to communicate with a SQL database.
- A JDBC driver is a Java class that implements the JDBC"s java.sql.Driver interface.
- 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:
- DriverManager
- Connection
- Statement
- PreparedStatement
- CallableStatement
- ResultSet
- SQLException