public class ConnectionTest1 {
//方式一
@Test
public void test() throws SQLException {
Driver driver = new com.mysql.cj.jdbc.Driver();
//在mysql中会显示时区异常
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
//jdbc:mysql:协议
//localhost:ip地址
//3306:默认mysql的端口号
//test:test数据库
//将用户名和密码封装在Properties中
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password","were");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
//方式二 : 对方式一的迭代
//为了提高可移植性,我们不希望出现第三方API
//解决方法:使用反射
@Test
public void test2() throws Exception {
//1、获取Driver实现类的对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver)clazz.newInstance();
//2、提供要连接的书库
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
//3、提供连接需要的用户名和密码
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","were");
//4、获取连接
Connection conn = driver.connect(url,info);
System.out.println(conn);
}
//方式三:使用DriverManager替换Driver
@Test
public void test3() throws Exception {
//1、获取Driver实现类的对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver)clazz.newInstance();
//2、注册驱动
DriverManager.registerDriver(driver);
//3、提供另外三个获取连接的基本信息
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String user = "root";
String password = "were";
//4、获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
//方式四:在三的基础上进行优化
//
@Test
public void test4() throws Exception {
//1、提供另外三个获取连接的基本信息
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String user = "root";
String password = "were";
//2、加载Driver驱动(在加载时,静态代码块已经帮我们注册了驱动)
//加载驱动在mysql中也可以省略,但一般不省略(提高移植性)
Class.forName("com.mysql.cj.jdbc.Driver");
/*
在mysql.cj.jdbc的Driver实现类中,声明了如下操作
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
*/
//3、获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
//方式五:(final版)
// 将数据库连接需要的4个基本信息声明在被指文件中,通过读取配置文件,获取连接
/*
此方法的好处:
1、实现了数据和代码的分离,实现了解耦
2、如果需要修改配置文件信息,可以避免程序重新打包。
*/
@Test
public void test5() throws Exception {
//1、读取配置文件中的4个基本信息
InputStream is = ConnectionTest1.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//2、加载驱动
Class clazz = Class.forName(driverClass);
//3、获取连接
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
}
}
JDBC 获取数据库连接的五种方式
最新推荐文章于 2022-09-25 20:47:26 发布