我們是否可以創建一個資料庫連接類,該類允許我們僅更改配置文件,然後使用資料庫?我做了這個類的原型,這很簡單。但是這個主意很好,總是使用一個非常簡單的jar文件來獲取安裝資料庫,然後可以執行SQL查詢操作。
這是調用DB類的代碼:
packagecom.programcreek.test;
importjava.io.IOException;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Properties;
importcom.programcreek.db.DB;
publicclassMain {
publicstaticvoidmain(String []args){
// to read url, username, password from configuration file
Properties configFile = newProperties();
String url = "";
String user_name = "";
String password = "";
String database = "";
configFile.load(Main.class.getClassLoader().getResourceAsStream("config.properties"));
url = configFile.getProperty("url");
database = configFile.getProperty("database");
user_name = configFile.getProperty("user_name");
password = configFile.getProperty("password");
} catch(IOException e1) {
e1.printStackTrace();
//instantiate a DB object
DB db = newDB(url + database, user_name, password);
ResultSet rs = db.runSql("select * from user");
while(rs.next()){
System.out.println(rs.getString("user_name"));
}}
這是這個想法的原型,一個完整的資料庫連接類應該能夠:
1)連接不同的資料庫,例如SQLServer,Accss等
2)具有runDB()函數,可以使用數組執行ADD,UPDATE,DELETE操作。以update為例,runDB(UPDATE,data),其中data是一個映射數組。
3)具有我以前的文章中顯示的日誌功能。
最後,開發這麼多年我也總結了一套學習Java的資料與面試題,如果你在技術上面想提升自己的話,可以關注我,私信發送領取資料或者在評論區留下自己的聯繫方式,有時間記得幫我點下轉發讓跟多的人看到哦。