您的位置:首页 > 编程语言 > Java开发

皮皮java笔记——数据库连接DriverManager

2017-02-25 15:00 155 查看
一、简单连接
/**
* DriverManager 是驱动的管理类.
* 1). 可以通过重载的 getConnection() 方法获取数据库连接. 较为方便
* 2). 可以同时管理多个驱动程序: 若注册了多个数据库连接, 则调用 getConnection()
* 方法时传入的参数不同, 即返回不同的数据库连接。
* @throws Exception
*/
@Test
public void testDriverManager() throws Exception{
//1. 准备连接数据库的 4 个字符串.
//驱动的全类名.
String driverClass = "com.mysql.jdbc.Driver";
//JDBC URL
String jdbcUrl = "jdbc:mysql://localhost:3306/namelist";
//user
String user = "root";
//password
String password = "123";

//2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
Class.forName(driverClass);

//3. 通过 DriverManager 的 getConnection() 方法获取数据库连接.
Connection connection =
DriverManager.getConnection(jdbcUrl, user, password);
System.out.println(connection);

}


二、通用连接

public Connection getConnection2() throws Exception{
//1. 准备连接数据库的 4 个字符串.
//1). 创建 Properties 对象
Properties properties = new Properties();

//2). 获取 jdbc.properties 对应的输入流
InputStream in =
this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");

//3). 加载 2) 对应的输入流
properties.load(in);

//4). 具体决定 user, password 等4 个字符串.
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String Url = properties.getProperty("url");
String driver = properties.getProperty("driver");

//2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
Class.forName(driver);

//3. 通过 DriverManager 的 getConnection() 方法获取数据库连接.
return DriverManager.getConnection(Url, user, password);
}

jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql;//localhost:3306/namelist
user=root
password=123
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 数据库