1. 获取连接的四个要素:
- 获取Driver接口的实现类(需要导入jar包)
- 获取url
- 获取用户名
- 获取密码
2.获取连接的方式
共有五种方式获取MySQL连接,此处只举例一种,这种方式耦合最低
public void testConnection5() throws Exception {
//1.加载配置文件
InputStream is = ClassLoader.getSystemClassLoader.getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
//2.获取配置信息(四个要素)
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//3.加载驱动
Class.forName(driverClass);
//4.获取连接
Connection con = DriverManager.getConnection(url,user,password);
System.out.println(con);
}
其中,配置文件声明在工程的src目录下:【jdbc.properties】
user=root
password=root
url=jdbc:mysql://localhost:3306/mysqltest?characterEncoding=utf8
driverClass=com.mysql.jdbc.Driver
注意:配置文件url中,如果JDBC 程序与服务器端的字符集不一致,会导致乱码,那么可以通过参数指定服务器端的字符集 ‘?characterEncoding=utf8’