前言
数据库连接一般有一下五种方式,最常用的方式为方式四、方式五,其他的也可以了解掌握。
举例:
数据库:db01
用户:root
密码:123456
- 方式一
//获取 Driver 实现类对象
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/db01";
Properties info = new Properties();
info.setProperty("user" , "root");
info.setProperty("password", "123456");
Connection conn = driver.connect(url, info);
if (conn != null){
System.out.println("连接成功。");
}
缺点:直接使用com.mysql.jdbc.Driver(),属于静态加载,灵活性差
- 方式二
//利用反射
Class cls = Class.forName("com.mysql.jdbc.Driver");
Driver driver =(Driver) cls.newInstance();
String url = "jdbc:mysql://localhost:3306/db01";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password","123456");
Connection conn = driver.connect(url, info);
if (conn != null) {
System.out.println("连接成功。");
}
利用了反射机制,属于动态加载方式,相对方式一提高了灵活性。
- 方式三
//使用 DriverManager替换 Driver
Class cls = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) cls.newInstance();
String url = "jdbc:mysql://localhost:3306/db01";
String user = "root";
String password = "123456";
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("连接成功。");
}
- 方式四
//使用 Class.forName() 自动完成注册驱动,简化代码
//原因:Driver类有静态代码块在类加载时自动执行了
//语句 DriverManager.registerDriver(new Driver());
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db01";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("连接成功。");
}
提示:
1. mysqL驱动5.1.6可以无需CLass . forName(“com.mysql.jdbc.Driver”)。
2. 从jdk1.5 以后使用了jdbc4,不再需要显示调用class.forName()注册驱动而是自动调用驱动jar包下META-INF\services\java.sql.Driver文本中的类名称
去注册。
3. 建议还是写上CLass . forName(“com.mysql.jdbc.Driver”),更加明确。
- 方式五
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
Class.forName(driver);//建议写上
Connection conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("连接成功。");
}
mysql.properties文件: