[英]How to externalize strings in the SQL Connection class
我是 Java 編程的新手。 我有一個連接到我的數據庫的 SQL 連接類。
我的導師審查了我的代碼,他讓我“使用屬性文件外部化字符串”。 我不確定他的意思是什么以及如何去做。
我在網上對此進行了研究,並找到了有關 eclipse 向導和國際化的文章。 這讓我更加困惑。我不確定我是否應該遵循它。
我的 SQL Connection 類看起來像這樣。
public class SQLConnection {
Connection conn = null;
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:xxxdbnamexxx.db");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
我希望連接類能夠像通常在字符串外部化之后那樣返回連接。
如果有幫助,我會使用 Eclipse IDE。
您的指導者意味着您的應用程序應該從屬性文件(或類似文件)中獲取字符串“ jdbc:sqlite:xxxdbnamexxx.db”以及可能的“ org.sqlite.JDBC”,而不是將其硬連接到代碼中。
這將允許您的應用程序用戶連接到其他數據庫,而無需修改源代碼。 他們所需要做的就是修改包含config屬性的屬性文件。
現在有爭議的是,究竟需要將哪些內容具體化。 要考慮的一件事是您的代碼可能是特定於SQLite的,這是因為數據庫將始終是SQLite,或者因為您依賴於特定於SQLite的SQL或行為。 因此,尚不清楚驅動程序類名稱( "org.sqlite.JDBC"
)是否應作為參數。
進行外部化的方法有很多種,但是簡單的方法是使用java.util.Properties
對象及其加載和保存方法。 有關詳細信息,請參見javadocs 。
這與國際化無關,在國際化中,應用程序從“資源束”中獲取用戶消息,具體取決於應用程序在其中運行的語言環境。
我不確定是否有一種簡單的方法。 但是您可以這樣做:
//Properties is a class:
Properties prop=new Properties();
//read file
InputStream in =
BaseDao.class.getClassLoader().getResourceAsStream("jdbc.properties");
prop.load(in);
//load file
String userName = prop.getProperty("userName");
String pwd = prop.getProperty("pwd");
String url = prop.getProperty("url");
String driver = prop.getProperty("driver");
// database driver
Class.forName(driver);
// get connection
Connection conn = DriverManager.getConnection(url, userName, pwd);
並創建一個名為“ jdbc.properties”的新文件,該文件位於資源目錄的根目錄中:
userName=root
pwd=password
// sqlite driver name
driver=org.sqlite.JDBC
// address of your database
url=jdbc:sqlite:personName.db
DriverManager.html#getConnection
是重載的方法。 您正在使用接受單個字符串的簡單版本 。 存在其他版本,例如接受URL,用戶名和密碼的版本 。
您可以像這樣使用它:
// The three arguments are here just for demonstration. Read them from a file,
// pass them as environment variables or as user input.
String url = "jdbc:sqlite:xxxdbnamexxx.db";
String username = "dbuser";
String password = "secret-password";
Connection conn = DriveManager.getConnection(url, username, password);
你不應該直接把這些三串代碼內。 將其放入代碼可以讀取的外部文件中,或將其作為環境變量傳遞給程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.