步骤如下:
- 准备数据
所要加载的驱动类
user
password
url
··· - 加载驱动
Class.forName(driverClass)//无需注册,Driver类已经为我们注册好了,直接加载进来即可)。 - 调用DriverManager类的getConnection方法连接Mysql数据库
DriverManager.getConnection(url, user, password)
源代码
package lesson1;
import static org.junit.Assert.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import org.junit.Test;
public class JDBCtest {
@Test
public void DriverManager()
{
//准备数据
String driverClass=null;
String url=null;
String url2=null;
String user=null;
String password=null;
try {
Properties pro=new Properties();
InputStream in=this.getClass().getResourceAsStream("./JDBCvalue2");
pro.load(in);
user=pro.getProperty("user");
url=pro.getProperty("url");
url2=pro.getProperty("url2");
password=pro.getProperty("password");
driverClass=pro.getProperty("driverClass");
Class.forName(driverClass);//加载Driver驱动
Connection connection1=DriverManager.getConnection(url, user, password);//调用getConnection方法连接驱动
Connection connection2=DriverManager.getConnection(url2, user, password);//调用getConnection方法连接驱动
System.out.println(connection1);
System.out.println(connection2);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}catch(SQLException e) {
System.out.println(e.getMessage());
}catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}catch (IOException e) {
System.out.println(e.getMessage());
}
}
}