JDBC连接MySQL的五种方式
JDBC连接数据库的五种方式
1.使用Driver连接:
public void con1() throws Exception { // 获取驱动 Driver driver = new Driver(); String url = "jdbc:mysql://localhost:3306/hsp_db02"; Properties properties = new Properties(); properties.setProperty("user", "root"); properties.setProperty("password", "abc123"); // 链接数据库 Connection connect = driver.connect(url, properties); // 关闭数据库连接 connect.close(); }
2.使用反射连接:
public void con2() throws Exception { // 得到驱动文件 Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) aClass.newInstance(); // 连接数据库 String url = "jdbc:mysql://localhost:3306/hsp_db02"; Properties properties = new Properties(); properties.setProperty("user", "root"); properties.setProperty("password", "abc123"); Connection connect = driver.connect(url, properties); // 关闭数据库连接 connect.close(); }
3.使用DriverManager连接:
public void con3() throws Exception { Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) aClass.newInstance(); // 链接数据库 String url = "jdbc:mysql://localhost:3306/hsp_db02"; String user = "root"; String password = "abc123"; // 注册驱动 DriverManager.registerDriver(driver); // 连接数据库 Connection connection = DriverManager.getConnection(url, user, password); // 关闭数据库连接 connection.close(); }
// 4.简化DriverManager连接
public void con4() throws Exception { /* * 使用反射加载类也可以省略。 * 解释:因为驱动jar包的META-INF文件夹下的services下的 * java.sql.Driver写了"com.mysql.cj.jdbc.Driver" * 他的内部文件会自动加载该类 */ Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver"); // 链接数据库 String url = "jdbc:mysql://localhost:3306/hsp_db02"; String user = "root"; String password = "abc123"; // 连接数据库 /* * 为什么不将Driver注册进DriverManager都能连接数据库? * 解释:因为Driver类里有一个静态代码块 * 在加载类的时候就自动注册进了DriverManager */ Connection connection = DriverManager.getConnection(url, user, password); // 关闭数据库连接 connection.close(); }
// 5.使用配置文件连接数据库
public void con5() throws Exception { // 准备拿配置文件里的信息 Properties properties = new Properties(); // 读取配置文件,已在src创建mysql80,并且填入key-value properties.load(new FileInputStream("src\mysql80.properties")); String driver = properties.getProperty("driver"); Class<?> aClass = Class.forName(driver); String url = properties.getProperty("url"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); // 连接数据库 Connection connection = DriverManager.getConnection(url, user, password); // 关闭数据库连接 connection.close(); }