连接池配置文件db.properties配置
1.新建一个普通文件->改名为db.properties(后缀)手动添加属性
一般为数据库驱动类、数据库连接地址、用户名、用户密码
driver=com.mysql.jdbc.Driver url=jdbc\:mysql\://localhost\:3306/bookshop username=root password=root
2.建立一个包名为until的专门储存数据连接类,里面添加main方法进行测试
package com.bk.until; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * Title: DbConn.java * Description: 数据库链接类 * @author tiankuan * @created 2016-12-21 下午8:31:05 */ public class DbConn { private static String username=null; private static String password=null; private static String driver=null; private static String url=null; /** * 静态代码块 */ static{ Properties ps=new Properties(); try { ps.load(DbConn.class.getResourceAsStream("/db.properties")); username=ps.getProperty("username"); password=ps.getProperty("password"); driver=ps.getProperty("driver"); url=ps.getProperty("url"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * * @discription 获取数据库连接 导入包为SQL 非MYSQLJDBC * @author tiankuan * @created 2016-12-21 下午8:58:59 * @return 返回数据库连接 */ public static Connection getConn(){ Connection con=null; try { Class.forName(driver); con = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con ; } /** * * @discription 关闭数据库 * @author tiankuan * @created 2016-12-21 下午9:40:36 * @param con * @return connection */ public static Connection closeCon(Connection con){ if (con!=null) { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return con; } /** * * @discription 数据库测试方法 * @author tiankuan * @created 2016-12-21 下午9:41:16 * @param args */ public static void main(String[] args) { try { DbConn.getConn(); System.out.println("数据库连接成功"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }