Java Web开发使用配置文件链接数据库

来源:互联网 发布:公司财务报表软件 编辑:程序博客网 时间:2024/05/13 07:58

昨天转载的一篇博客:《Tomcat下配置数据源链接数据库》,但是按照文中的方法进行实践以后,发现Tomcat启动过程中一直有报错。现在我也没有搞清楚原因,但肯定是配置文件的问题。

所以我又尝试了另外一种方法:利用Property文件进行数据库元数据的存储,然后在程序中动态进行连接。

首先,新建Property文件。我的路径如下:src/config/dbconfig.properties。

文件内容如下:(我以PostgreSQL数据库为例,其中的名称根据你自己的情况更改。MySQL数据库类似)

url=jdbc\:postgresql\://localhost\:5432/dbName
driver=org.postgresql.Driver
user=userName
password=password

然后,进行数据库的连接,连接代码如下:

Properties dbProperties = new Properties();dbProperties.load(DBTool.class.getResourceAsStream("/config/dbconfig.properties"));String url = dbProperties.getProperty("url");String driver = dbProperties.getProperty("driver");String user = dbProperties.getProperty("user");String password = dbProperties.getProperty("password");Class.forName(driver);  Connection dbConnection = DriverManager.getConnection(url, user, password); 

这样就得到了数据库的连接对象dbConnection,然后就可以对数据库进行操作了!

0 0
原创粉丝点击