1. 程式人生 > >數據庫連接池連接方法:

數據庫連接池連接方法:

tom 數據庫連接 -c auth 代碼 cat idle web-inf blog

先要下載好數據庫連接驅動jar文件:mysql-connector-java-5.1.22-bin 放在tomcat的lib文件夾下,並在然後根據以下兩種方法加以配置:

1、全局方法:
在tomcat的conf目錄下打開context.xml加入代碼:ConnectionPool為連接池名字,可隨便取,但是要對應;newsmanagersystem為數據庫名
<Context>
<Resource
name = "jdbc/myconn"
auth = "Container"
type = "javax.sql.DataSource"
password = "root"
driverClassName = "com.mysql.jdbc.Driver"
maxIdle = "10"
maxWait = "1000"
username = "root"
url = "jdbc:MYSQL://localhost:3306/study?characterEncoding=GBK"
maxActive = "8"/>

<WatchedResource>Web-INF/web.xml</WatchedResource>
</Context>

然後在工程的web.xml文件中加入代碼:
<resource-ref>
<description>GuestBook</description>
<res-ref-name>jdbc/myconn</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/myconn"
auth = "Container"
type = "javax.sql.DataSource"
password = "root"
driverClassName = "com.mysql.jdbc.Driver"
maxIdle = "10"
maxWait = "1000"
username = "root"
url = "jdbc:MYSQL://localhost:3306/newsmanagersystem?characterEncoding=GBK"
maxActive = "8"/>

<WatchedResource>Web-INF/web.xml</WatchedResource>
</Context>


根據以上兩種方法就可在程序中創建數據源對象:
Context ctx = new InitialContext();
Context ctxing = (Context) ctx.lookup("java:comp/env");
//獲取連接池對象
DataSource ds =(DataSource)ctxing.lookup("jdbc/ConnectionPool");
//創建連接
Connection conn = ds.getConnection();
Statement st= conn.createStatement();

數據庫連接池連接方法: