操作数据库的基本类
| 10 | * 操作数据库的基本类 |
| 11 | */ |
| 12 | public class BaseDao { |
| 13 | static { |
| 14 | init(); |
| 15 | } |
| 16 | |
| 17 | private static String driver; |
| 18 | private static String url; |
| 19 | private static String user; |
| 20 | private static String password; |
| 21 | |
| 22 | /** |
| 23 | * 读取配置文件对数据库初始化,使用静态代码块在类加载前调用 |
| 24 | */ |
| 25 | public static void init() { |
| 26 | InputStream resourceAsStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); |
| 27 | Properties properties = new Properties(); |
| 28 | |
| 29 | try { |
| 30 | properties.load(resourceAsStream); |
| 31 | } catch (IOException e) { |
| 32 | e.printStackTrace(); |
| 33 | } |
| 34 | driver = properties.getProperty("driver"); |
| 35 | url = properties.getProperty("url"); |
| 36 | user = properties.getProperty("user"); |
| 37 | password = properties.getProperty("password"); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * 此方法获得一个connection连接 |
| 42 | * |
| 43 | * @return |
| 44 | */ |
| 45 | public static Connection getConnection() { |
| 46 | //加载驱动 |
| 47 | try { |
| 48 | Class.forName(driver); |
| 49 | } catch (ClassNotFoundException e) { |
| 50 | e.printStackTrace(); |
| 51 | } |
| 52 | //获取连接 |
| 53 | Connection connection = null; |
| 54 | try { |
| 55 | connection = DriverManager.getConnection(url, user, password); |
| 56 | } catch (SQLException throwables) { |
| 57 | throwables.printStackTrace(); |
| 58 | } |
| 59 | return connection; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * 查询操作 |
| 64 | * 获取service层统一的connection对象,补充预编译sql语句,返回结果集 |
| 65 | * @param connection |
| 66 | * @param pstm |
| 67 | * @param resultSet |
| 68 | * @param sql |
| 69 | * @param params |