通过DriverManager接口获取连接

  1. 云栖社区>
  2. 博客>
  3. 正文

通过DriverManager接口获取连接

行走的菠萝 2018-11-02 14:37:06 浏览505
展开阅读全文
public class JDBCDriverManager_getConnection {
//通过DriverManager接口获取连接,实际开发基本不用,DriverManager是驱动管理类
public static void main(String[] args) throws Exception {
new JDBCDriverManager_getConnection().getConnection(); 
}
public Connection getConnection() throws Exception{
//连接参数
String driverClass = null;
String url=null;
String user = null;
String password = null;
Properties properties = new Properties();//使用Properties
properties.load(getClass().getClassLoader().getResourceAsStream("jdbc.properties"));//读取配置文本
//参数变量赋值
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driverClass = properties.getProperty("driverClass");
Class.forName(driverClass);//注入驱动
Connection connection = DriverManager.getConnection(url, user, password);//获取连接
return connection;
/*
* 以下是jdbc.properties  配置文件内容,配置文件需放在src根目录下
* driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3307/Test
user = root
password = 3306
*/
}
}

网友评论

登录后评论
0/500
评论