<span style="font-family:KaiTi_GB2312;font-size:24px;">一般在项目当中,我们要多次与数据库进行交互 </span>
<span style="font-family:KaiTi_GB2312;font-size:24px;">public void testDriver() throws SQLException {
// 1.创建一个Driver的实例类对象
Driver driver = new com.mysql.jdbc.Driver();
// 2.链接的基本准备。
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "root");
// 3.通过driver的connect方法获取链接
Connection connect = driver.connect(url, info);
System.out.println(connect);
}</span>
具体的流程是:
1.创建一个driver的对象
2.定义url和info信息
3.通过driver的connect方法进行连接
下面的是一个通用的方法,在项目根目录下创建一个jdbc.properties配置文件
在配置文件中定义url,user,password,以及driver。
jdbc.properties
<span style="font-family:KaiTi_GB2312;font-size:24px;">driver=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql://localhost:3306/test
user=root
password=root
</span>
通用的方法:
<span style="font-family:KaiTi_GB2312;font-size:24px;">public Connection getConnection() throws InstantiationException,
IllegalAccessException, ClassNotFoundException, SQLException,
IOException {
String driverclass = null;
String jdbcurl = null;
String user = null;
String password = null;
// 读取路径下的jdbc.properties
InputStream in = getClass().getClassLoader().getResourceAsStream(
"jdbc.properties");//加载路径
Properties properties = new Properties();
properties.load(in);
driverclass = properties.getProperty("driver");
jdbcurl = properties.getProperty("jdbcurl");
user = properties.getProperty("user");
password = properties.getProperty("password");
Driver driver = (Driver) Class.forName(driverclass).newInstance();//反射
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
Connection conn = driver.connect(jdbcurl, info);
return conn;
}</span>
这样就可以不用修改源代码来更改链接信息,只用修改配置文件就可以