天天看點

資料庫連接配接資訊寫在properties檔案,讀取配置檔案

這裡是使用mysql資料庫。

使用一個mysql.ini檔案(就是一個properties檔案)來儲存資料庫連接配接資訊,這是比較成熟的做法———但需要把應用程式

從開發環境移植到生産環境時,無須修改源代碼,隻需要修改mysql.ini配置檔案即可。

凡凡第一看到時候,以為是mysql.ini自帶檔案,就把mysql裡的複制過去。(o(╯□╰)o囧了!!)

下圖展示檔案及其存放位置。

建立檔案:

資料庫連接配接資訊寫在properties檔案,讀取配置檔案

檔案内容:

資料庫連接配接資訊寫在properties檔案,讀取配置檔案

檔案存放:

①與所要使用類的同級

資料庫連接配接資訊寫在properties檔案,讀取配置檔案

②直接放在src下

在web中放在src的配置檔案會直接加載到classes中

而Java的properties檔案需要放到classpath下面,這樣程式才能讀取到,有關classpath實際上就是java類或者庫的存放路徑,在java工程中,properties放到class檔案一塊

原因:讀取檔案是使用類加載器,而類加載器讀取檔案,預設是在src下。

class檔案一塊

操作:

資料庫連接配接資訊寫在properties檔案,讀取配置檔案

使用如下:

public class ExecuteDDL
{
    private String driver;
    private String url;
    private String user;
    private String pwd;
    public void initParam(String paramFile) throws Exception
    {

        Properties props= new Properties();
        props.load(new FileInputStream(paramFile));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }
    public void createTable(String sql) throws Exception
    {

        Class.forName(driver);
        try(

                Connection conn = DriverManager.getConnection(url, user, pwd);

                Statement stmt = conn.createStatement())
        {

            stmt.executeUpdate(sql);
        }

    }
    public static void main(String []args) throws Exception
    {
        ExecuteDDL ed = new ExecuteDDL();
        ed.initParam("src/com/yyf/JDBC/db.properties");
        ed.createTable("create table jdbc_test" +
                        "(jdbc_id int auto_increment primary key,"
                        +"jdbc_name varchar(255)"
                        +"jdbc_desc text);"
        );
        System.out.println("成功");
    }
}