在使用servlet时读取database.properties数据库配置文件信息方法

来源:互联网 发布:64位 mysql 编辑:程序博客网 时间:2024/06/14 11:59

在用servlet做一个简单的项目时,一般数据库文件要么写在xml文件里要么写在java文件中,此次为了方便特意写在database.properties文件中。下面是项目路径和读取database.properties文件代码。

这里写图片描述

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.Locale;import java.util.ResourceBundle;public class DbHelper {    static String user;    static String password;    static String url;    static {            try {                ResourceBundle rb = ResourceBundle.getBundle("database",Locale.getDefault());                user = rb.getString("user");                password = rb.getString("password");                url = rb.getString("url");            } catch (Exception ex) {                System.err.println("read resource error!");            }        }    Connection connection = null;    Statement statement = null;    ResultSet rs = null;    public DbHelper() {        try {            Class.forName("com.mysql.jdbc.Driver")                    .newInstance();        } catch (InstantiationException e) {            e.printStackTrace();        } catch (IllegalAccessException e) {            e.printStackTrace();        } catch (ClassNotFoundException e) {            e.printStackTrace();        }    }    public Connection getConnect() {        try {            this.connection = DriverManager.getConnection(url, user, password);            this.statement = this.connection.createStatement(1005, 1008);        } catch (Exception e) {            e.printStackTrace();            System.out.println("驱动类加载失败!");            return null;        }        return this.connection;    }}
0 0
原创粉丝点击