五种方式依次逐渐优化,若无时间,直接记住最后一种即可
public class ConnectionTest {
@Test
public void Test1() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/test"; //要连接的数据库test
//用户名密码在propertieszhogn
Properties info = new Properties();
info.setProperty("root", "root");
Connection connection = driver.connect(url,info);
System.out.println(connection);
}
@Test
public void test2() throws Exception {
//test1的迭代版,程序中没有第三方API 提高可移植性;
//1 反射获取Driver的实现类对象==换数据库方便
String DriverType = "com.mysql.jdbc.Driver";
Class clazz = Class.forName(DriverType);
Driver driver = (Driver) clazz.newInstance();
//2 提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/test"; //要连接的数据库test
//3 提供用户名密码
Properties info = new Properties();
info.setProperty("root", "root");
//4 开始连接
Connection connection = driver.connect(url,info);
System.out.println(connection);
}
@Test
public void test3() throws Exception {
//DriverManager 替换
//1 获取Driver实现类对象
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//提供信息
String url = "jdbc:mysql://localhost:3306/test"; //要连接的数据库test
String uname="root";
String pwd="root";
//注册驱动
DriverManager.registerDriver(driver);
//获取链接
Connection connection = DriverManager.getConnection(url,uname,pwd);
System.out.println(connection);
}
@Test
public void test4() throws Exception {
//只加载驱动,不用注册
//提供信息
String url = "jdbc:mysql://localhost:3306/test"; //要连接的数据库test
String uname="root";
String pwd="root";
//获取Driver实现类对象//mysql.Driver自带的静态代码执行了对象创建
Class.forName("com.mysql.jdbc.Driver");
//获取链接
Connection connection = DriverManager.getConnection(url,uname,pwd);
System.out.println(connection);
}
@Test//通过配置文件加载
public void finalConn() throws Exception {
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String username = pros.getProperty("username");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String classDriver = pros.getProperty("driverClass");
Class.forName(classDriver);
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
}
}
jdbc.properties 的内容为:
username=root
password=root
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
建议将其创建在src目录下