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

来源:互联网 发布:python mako 编辑:程序博客网 时间:2024/05/26 19:17
一、简单连接
/** * DriverManager 是驱动的管理类.  * 1). 可以通过重载的 getConnection() 方法获取数据库连接. 较为方便 * 2). 可以同时管理多个驱动程序: 若注册了多个数据库连接, 则调用 getConnection() * 方法时传入的参数不同, 即返回不同的数据库连接。  * @throws Exception  */@Testpublic void testDriverManager() throws Exception{//1. 准备连接数据库的 4 个字符串. //驱动的全类名.String driverClass = "com.mysql.jdbc.Driver";//JDBC URLString jdbcUrl = "jdbc:mysql://localhost:3306/namelist";//userString user = "root";//passwordString 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.Driverurl=jdbc:mysql;//localhost:3306/namelistuser=rootpassword=123


1 0