我有一個獨立的類,我保持連接。在幾個地方我打電話connection = ConnectionManager.getConnection();
,並做一些查詢相關行動爲靜態或非靜態連接創建對象的實例變量更好嗎
public class TableWithBottomLine extends JPanel implements TableModelListener {
private Connection connection = null;
private Statement stmt = null;
private PreparedStatement prepStmt = null;
private ResultSet resSet = null;
在同一個「主」類:
public class ConnectionManager {
private static String url = "jdbc:mysql://localhost/finance";
private static String driverName = "com.mysql.jdbc.Driver";
private static String username = "root";
private static String password = "";
private static Connection con;
public static Connection getConnection() {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
System.out.println("Driver not found.");
}
return con;
}
}
在其他的「主」類我。現在我想知道,將這些實例變量設置爲靜態會更好嗎?爲了性能/安全性。如果有人能分享他們的見解,會很開心。
IMO它總是壞在這個circumnstances使用靜態。改用連接池(如[dbcp](https://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi)) – BackSlash
都不是。它應該是一個與線程池關聯的局部變量。 – EJP
@EJP謝謝你的回答。我遵循你的建議。兩個問題。 1.使用局部變量執行作業時,代碼中的這些額外行。我認爲重複的代碼不好?和2.在使用它之前,我必須通過給定一個空值來懶惰地創建本地連接變量嗎? – Paul