推薦開發環境: JDK+ Tomcat+Mysql+Myeclipse(按照安裝順序排列)。
先安裝好上面的開發環境並進行相關配置,最主要的是path路徑要添加。然后進行下面的操作。
數據庫連接池連接方法:
先要下載好數據庫連接驅動:mysql-connector-java-5.1.22-bin 放在tomcat的lib文件夾下,並在然后根據以下兩種方法加以配置:
1、全局方法:
在tomcat的conf目錄下打開context.xml加入代碼:ConnectionPool為連接池名字,可隨便取,但是要對應;study為數據庫名
<Context>
<Resource
name = "jdbc/ConnectionPool"
auth = "Container"
type = "javax.sql.DataSource"
password = "123456"
driverClassName = "com.mysql.jdbc.Driver"
maxIdle = "2"
maxWait = "5000"
username = "root"
url = "jdbc:MYSQL://localhost:3306/study?characterEncoding=GBK"
maxActive = "4"/>
<WatchedResource>Web-INF/web.xml</WatchedResource>
</Context>
然后在工程的web.xml文件中加入代碼:
<resource-ref>
<description>GuestBook</description>
<res-ref-name>jdbc/ConnectionPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
2、對某一個Web項目的方法:
在META-INF文件夾下context.xml文件中加入代碼:
<Context>
<Resource
name = "jdbc/ConnectionPool"
auth = "Container"
type = "javax.sql.DataSource"
password = "123456"
driverClassName = "com.mysql.jdbc.Driver"
maxIdle = "2"
maxWait = "5000"
username = "root"
url = "jdbc:MYSQL://localhost:3306/study?characterEncoding=GBK"
maxActive = "4"/>
<WatchedResource>Web-INF/web.xml</WatchedResource>
</Context>
根據以上兩種方法就可在程序中創建數據源對象:(下面代碼添加到工程文件中)
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
//獲取連接池對象
DataSource ds =(DataSource)ctx.lookup("jdbc/ConnectionPool");
//創建連接
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
如果配置不好或哪里出了問題那就悲劇了,很有可能和我一樣搞了一下午都搞不出來。。