標籤:url 配置 set 資料庫連接池 null rgs new private 添加
Java JDBC使用設定檔串連資料庫:
建立尾碼名為:.properties的檔案,檔案內容包括,資料庫驅動、串連的資料庫地址、使用者名稱、密碼……
以Mysql為例建立config.properties設定檔其內容如下:
DRIVER_CLASS=com.mysql.jdbc.Driver
CONNECTION_URL=jdbc:mysql://localhost:3306/test
CONNECTION_USERNAME=root
CONNECTION_PASSWORD=root
建立串連資料庫類:
例如:
public class ConnectionFactory {
private static Properties prop;
private static final String CONFIGNAME = "config.properties";
private static List<Connection> conns;
private Connection conn;
public JDBCFactory() throws Exception{
conns = new ArrayList<Connection>();
prop = new Properties();
//載入設定檔
prop.load(this.getClass().getResourceAsStream(CONFIGNAME));
//擷取資料庫驅動
Class.forName(prop.getProperty("DRIVER_CLASS"));
//建立十個資料庫連接並放入List集合(conns),
//list集合(conns)相當於一個有十個資料庫連接的資料庫連接池
for (int i = 0; i < 10; i++) {
conn = DriverManager.getConnection(
prop.getProperty("CONNECTION_URL"),
prop.getProperty("CONNECTION_USERNAME"),
prop.getProperty("CONNECTION_PASSWORD"));
conns.add(conn);
}
}
//從List集合(conns)中擷取資料庫連接
public Connection getConnection(){
return conns.remove(0);
}
//已用完的資料庫連接從新添加到List集合(conns)中
public void close(Connection conn){
if(conn!=null){
conns.add(conn);
}
}
}
定義測試類別:
public class JDBCTest {
public static void main(String[] args) throws Exception {
//建立ConnectionFactory對象,同時建立資料庫連接池
ConnectionFactory cf = new ConnectionFactory();
//擷取資料庫連接
Connection conn = cf.getConnection();
//select sql語句
PreparedStatement ps = conn.prepareStatement("select * from user");
//執行sql語句
ResultSet rs = ps.executeQuery();
//迴圈輸入查詢到的內容
while(rs.next()){
//id username password 為查詢資料庫的欄位
System.out.println("id:"+rs.getInt("id")+
"Username:"+rs.getString("username")+
"Password:"+rs.getString("password"));
}
}
}
設定檔串連mysql資料庫