“获取数据库连接的方式二”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
(建立内容为“https://www.bilibili.com/video/BV1eJ411c7rf?p=8”的新页面)
 
 
(未显示同一用户的3个中间版本)
第1行: 第1行:
 
https://www.bilibili.com/video/BV1eJ411c7rf?p=8
 
https://www.bilibili.com/video/BV1eJ411c7rf?p=8
 +
 +
运用反射,不在当前类 import 第三方 package,不出现第三方jar 的API,拥有更好的移植性<syntaxhighlight lang="java">
 +
package io.github.jihch.connection;
 +
 +
import org.junit.Test;
 +
 +
import java.sql.Connection;
 +
import java.sql.Driver;
 +
import java.sql.SQLException;
 +
import java.util.Properties;
 +
 +
public class ConnectionTest2 {
 +
 +
    /**
 +
    * 方式二:
 +
    * 区别于第一种方式,这个方式不需要在当前类中 import 第三方 package
 +
    * @throws SQLException
 +
    */
 +
    @Test
 +
    public void testConnection2() throws SQLException, ClassNotFoundException, InstantiationException,
 +
            IllegalAccessException {
 +
 +
        //1.获取 Driver 实现类对象:使用反射来实现
 +
        Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
 +
        Driver driver = (Driver) clazz.newInstance();
 +
 +
        //2.提供要连接的数据库
 +
        String url = "jdbc:mysql://localhost:3306/guns";
 +
 +
        //将用户名和密码封装到 Properties 中
 +
        Properties info = new Properties();
 +
        info.setProperty("user", "root");
 +
        info.setProperty("password", "123456");
 +
 +
        Connection conn = driver.connect(url, info);
 +
 +
        System.out.println(conn);
 +
 +
    }
 +
 +
}
 +
</syntaxhighlight><syntaxhighlight lang="console">
 +
com.mysql.cj.jdbc.ConnectionImpl@4278a03f
 +
</syntaxhighlight>https://github.com/jihch/jdbc/blob/main/src/main/java/io/github/jihch/connection/ConnectionTest2.java

2022年12月14日 (三) 14:41的最新版本

https://www.bilibili.com/video/BV1eJ411c7rf?p=8

运用反射,不在当前类 import 第三方 package,不出现第三方jar 的API,拥有更好的移植性

package io.github.jihch.connection;

import org.junit.Test;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionTest2 {

    /**
     * 方式二:
     * 区别于第一种方式,这个方式不需要在当前类中 import 第三方 package
     * @throws SQLException
     */
    @Test
    public void testConnection2() throws SQLException, ClassNotFoundException, InstantiationException,
            IllegalAccessException {

        //1.获取 Driver 实现类对象:使用反射来实现
        Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

        //2.提供要连接的数据库
        String url = "jdbc:mysql://localhost:3306/guns";

        //将用户名和密码封装到 Properties 中
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "123456");

        Connection conn = driver.connect(url, info);

        System.out.println(conn);

    }

}
com.mysql.cj.jdbc.ConnectionImpl@4278a03f

https://github.com/jihch/jdbc/blob/main/src/main/java/io/github/jihch/connection/ConnectionTest2.java