方式一
public void connectionTest() throws SQLException {
//定义URL
String url = "jdbc:mysql://localhost:3306/test";
//创建driver
Driver driver = new com.mysql.jdbc. Driver();
//通过驱动来获取链接
Properties pro = new Properties();
pro.setProperty("user", "root");
pro.setProperty("password", "root");
Connection conn = driver.connect(url, pro);
System.out.println(conn);
}
这是最通俗的连接方式
问题是应用程序和Mysql的jdbc的实现类发生了直接的耦合
方式二
public void connectionTest2() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
//定义URL
String url = "jdbc:mysql://localhost:3306/test";
//创建driver
String driverStr = "com.mysql.jdbc.Driver";//Driver类的全类名
Driver driver = null;
driver =(Driver) Class.forName(driverStr).newInstance();
//通过驱动来获取链接
Properties pro = new Properties();
pro.setProperty("user", "root");
pro.setProperty("password", "root");
Connection conn = driver.connect(url, pro);
System.out.println(conn);
}
这种方式使用反了射机制来解除耦合
方式三
public void connectionTest3() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
//定义URL
String url = "jdbc:mysql://localhost:3306/test";
//创建driver
String driverStr = "com.mysql.jdbc.Driver";//Driver类的全类名
Driver driver = null;
driver =(Driver) Class.forName(driverStr).newInstance();
//注册驱动
DriverManager.registerDriver(driver);
//通过驱动来获取链接
Properties pro = new Properties();
pro.setProperty("user", "root");
pro.setProperty("password", "root");
Connection conn = driver.connect(url, pro);
System.out.println(conn);
}
这种 DriverManager使用注册驱动
方式四
public void connectionTest4() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
//定义URL
String url = "jdbc:mysql://localhost:3306/test";
//创建driver
String driverStr = "com.mysql.jdbc.Driver";//Driver类的全类名
//创建用户名和密码
String user = "root";
String password="root";
//加载mysql的Dirver
Class.forName(driverStr);
Connection conn = DriverManager.getConnection(url, user,password);
System.out.println(conn);
}
但是方式四的连接属性还是采用了硬编码的方式
方式五
编写一个jdbc.properties的配置文件
url=jdbc:mysql://localhost:3306/test
driver =com.mysql.jdbc.Driver
user=root
password=root
public void connectionTest5() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
//第一步加载配置文件
InputStream in =this.getClass().getClassLoader().getSystemResourceAsStream("jdbc.properties");
Properties pro = new Properties();
pro.load(in);
//定义URL
String url = pro.getProperty("url");
//从配置文件中获取链接属性
String driverStr = pro.getProperty("driver");//Driver类的全类名
String user = pro.getProperty("user");
String password=pro.getProperty("password");
//加载mysql的Dirver
Class.forName(driverStr);
Connection conn = DriverManager.getConnection(url, user,password);
System.out.println(conn);
}
这个就解决了硬编码问题