一、JDBC访问数据库需要用到的类、接口、方法
1、java.sql包DriverManager类,负责加载各种不同的驱动程序(Driver),并根据不同的请求,向调用者返回相应的数据库连接。驱动程序,会将自身加载到DriverManager中去。
2、在项目中导入对应的jar包, 通过java的反射机制,来给DirverManager,提供被加载的数据的驱动名称。
Class.forName(“数据库驱动名称【包名+类名】”);
Class.forName("com.mysql.jdbc.Driver") 名称来自jar包中Driver的java类的全名称
二、向调用者返回相应的数据库连接
Driver类中的静态方法getConnection(url,username,password)向调用者返回相应的数据库连接池
三、Driver和DriverManger加载驱动的具体实现
1、使用Driver硬编码实现
public class chapter1 {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
//创建驱动
Driver driver = new Driver();
String url = "jdbc:mysql://localhost:3306/666_db02";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "666");
//获得连接
Connection connection = driver.connect(url, info);
System.out.print("connected");
//记得随手关门
connection.close();
2、Driver添加配置文件后实现
反射创建driver,为后续创建properties配置文件时,提供Driver路径做准备。由硬编码优化为软编码。
//反射创建
Class c = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)c.newInstance();
String url = "jdbc:mysql://localhost:3306/ldj_db02";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "ldj");
Connection connection = driver.connect(url, info);
System.out.print("connected");
connection.close();
除了url,数据库登录所需的user和password外,driverPath就是之前反射所需用到的Driver包包路径。
#Thu Nov 18 16:49:38 CST 2021
url=jdbc\:mysql\://localhost\:3306/666_db02
driverPath=com.mysql.jdbc.Driver
user=root
password=666
以后只需要更换数据库,或者登录信息时,只要修改properties配置文件,不用修改源码。
//获取配置文件(包含Driver类路径、url配置、用户名、密码)
Properties info = new Properties();
info.load(new FileInputStream("src//driver.properties"));
Class c = Class.forName(info.getProperty("driverPath"));
Driver driver = (Driver)c.newInstance();
Connection connection = driver.connect(info.getProperty("url"), info);
System.out.print("connected");
connection.close();
3、driver注册到DriverManager中
DriverManager取代 Driver,对Driver统一管理,便于应对需要连接多个数据库的场景。
//获取配置文件(包含Driver类路径、url配置、用户名、密码)
Properties info = new Properties();
info.load(new FileInputStream("src//driver.properties"));
//将反射创建的driver注册到DriverManger
Class a = Class.forName(info.getProperty("driverPath"));
DriverManager.registerDriver((Driver)a.newInstance());
//由DriverManager来获得conection连接
Connection connection = DriverManager.getConnection(info.getProperty("url"),info);
System.out.print("connected");
connection.close();
4、简化driver注册
Driver类中的静态代码块:调用DriverManager注册了driver对象
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
mysql-connector-java-5.1.37-bin.jar中:META-INF/java.sql.Driver配置文件包含了Driver路径,使用JDBC时会直接创建driver。
Properties info = new Properties();
info.load(new FileInputStream("src//driver.properties"));
//反射加载driver,可省略(不推荐)
Class.forName(info.getProperty("driverPath"));
Connection connection = DriverManager.getConnection(info.getProperty("url"),info);
System.out.print("connected");
connection.close();