package util; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DBTool { private static String driver; private static String url; private static String user; private static String pwd; static { Properties pro = new Properties(); try { //加载db.properties文件 pro.load(DBTool.class.getClassLoader().getResourceAsStream("db.properties")); //读取连接参数 driver = pro.getProperty("driver"); url = pro.getProperty("url"); user = pro.getProperty("user"); pwd = pro.getProperty("pwd"); //注册驱动 Class.forName(driver); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("加载db.properties文件失败", e); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException("找不到此驱动", e); } } //连接数据库 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, pwd); } //关闭连接 public static void close( Connection conn ) { if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("关闭连接失败", e); } } } }
测试
/** * 测试DBTool类封装的连接数据库的方法 */ @Test public void test3() { Connection conn = null; try { //创建连接 conn = DBTool.getConnection(); //创建Statement Statement stat = conn.createStatement(); //SQL String sql = "insert into u_roles(role_name, remark) values('兜兜有糖', '测试的吧')"; //执行SQL int rows = stat.executeUpdate(sql); //返回的是增加/修改/删除的行数 System.out.println(rows); } catch (SQLException e) { e.printStackTrace(); } finally { DBTool.close(conn); } }