設定檔串連mysql資料庫

來源:互聯網
上載者:User

標籤: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資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.