單例模式:軟件設(shè)計模式踢械,定義是單例對象的類只能允許一個實(shí)例存在础米。
? ? ? ? 1)properties讀取配置文件
? ? ? ? ? ? Properties?pro = new Properties();
? ? ? ? ? ?pro.load(?ConfigManager.class.getClassLoader().getResourceAsStream(file));不能加任何符號 ,比如:空格
配置數(shù)據(jù)源—讀取數(shù)據(jù)源連接數(shù)據(jù)庫
用連接池的方式連接數(shù)據(jù)庫的幾大重要步驟:
步驟一:
1,將數(shù)據(jù)庫的mysql-connector-java-5.0.8-bin.jar文件拷到tomcat安裝目錄下的lib文件夾中规个。
2狰晚,在Tomcat的conf/context.xml
注意:在配置文件中不允許有中文,包括注釋內(nèi)的中文
auth="Container"? type="javax.sql.DataSource"? maxActive="100"?
maxIdle="30" maxWait="10000" username="root"? password="root"?
driverClassName="com.mysql.jdbc.Driver"?
url="jdbc:mysql://localhost:3306/mydb2"/>
其中:
name:表示你的連接池的名稱也就是你要訪問連接池的地址
auth:是連接池管理權(quán)屬性围俘,Container表示容器管理
type:是對象的類型
driverClassName:是數(shù)據(jù)庫驅(qū)動的名稱
url:是數(shù)據(jù)庫的地址
username:是登陸數(shù)據(jù)庫的用戶名
password:是登陸數(shù)據(jù)庫的密碼
maxIdle,最大空閑數(shù)机断,數(shù)據(jù)庫連接的最大空閑時間楷拳。超過空閑時間,數(shù)據(jù)庫連
接將被標(biāo)記為不可用吏奸,然后被釋放欢揖。設(shè)為0表示無限制。
MaxActive奋蔚,連接池的最大數(shù)據(jù)庫連接數(shù)她混。設(shè)為0表示無限制。
maxWait 泊碑,最大建立連接等待時間坤按。如果超過此時間將接到異常。設(shè)為-1表示
無限制馒过。
3臭脓,配置應(yīng)用程序的web.xml文件(可選)
jdbc/news
javax.sql.DataSource
Container
步驟二:
1,編寫java代碼腹忽,獲取與邏輯名相關(guān)聯(lián)的數(shù)據(jù)源對象?
關(guān)鍵代碼:
public Connection getConnection2() {
try {
//初始化上下文
Context cxt=new InitialContext();
//獲取與邏輯名相關(guān)聯(lián)的數(shù)據(jù)源對象
//是環(huán)境命名上下文(environment naming context(ENC)
Context ctx2=(Context) cxt.lookup("java:comp/env");
DataSource ds=(DataSource) ctx2.lookup("jdbc/news");
/*另一種寫法来累,兩種方法本質(zhì)是不一樣的
* DataSource ds=(DataSource)cxt.lookup("java:comp/env/jdbc/news");
*/
conn=ds.getConnection();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
步驟三:
1,編寫jsp頁面:驗(yàn)證數(shù)據(jù)源連接
關(guān)鍵代碼:
<%
BaseDao baseDao=new BaseDao();
Connection conn=baseDao.getConnection2();
%>
<%=conn %>