上次复习了java连接jdbc,把数据库的连接信息放到程序里,但是感觉这样b格不是太高,我们换个数据库用户不能总是修改程序中的代码吧,把这些信息放置到配置文件中多好。java中常用的配置文件是properties文件。
properties文件内容格式是以键值对的形式存在key=value,可以用”#“号来注释一行内容。
这里关于properties就不再多介绍,让我们通过程序来看吧。
程序写完了,但是要有个前提,没有properties文件我们怎么用啊。在src下新建一个db.properties文件,过程也不用多说,直接上图。
这里关于properties就不再多介绍,让我们通过程序来看吧。
点击(此处)折叠或打开
- public class BaseDao {
- // 获取配置信息
- public String getProperties(String key) {
- Properties pps = new Properties();
- try {
- BufferedInputStream in = new BufferedInputStream(
- new FileInputStream("src/db.properties"));
- pps.load(in);
- return pps.getProperty(key);
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * 连接数据库
- */
- Connection conn = null;
- BaseDao bd = null;
-
- public Connection getConnection() {
- try {
- bd = new BaseDao();
- Class.forName(bd.getProperties("drive"));
-
- conn = DriverManager.getConnection(bd.getProperties("url"),
- bd.getProperties("uid"), bd.getProperties("pwd"));
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return conn;
- }
-
- /**
- * 关闭数据库
- */
- public void closeConnection(Connection conn, PreparedStatement pstmt,
- ResultSet rs) {
-
- try {
- if (rs != null) {
- rs.close();
- }
- if (pstmt != null) {
- pstmt.close();
- }
- if (conn != null && !conn.isClosed()) {
- conn.close();
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
-
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876573/viewspace-1815450/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29876573/viewspace-1815450/