資料來源(串連池),資料來源串連
資料來源一般實現自javax.sql.DataSource介面,Spring、Struts、Hibernate等架構都有自己的資料來源,Tomcat中也內建了資料來源支援,Tomcat使用Jakarta-CommonsDatabase Connection Pool作為資料來源的實現,使用時只需按照Tomcat文檔配置即可
資料來源可以配置在server.xml中,也可以配置在context.xml中
在context.xml中配置資料來源
<Context cookies="true"> <Resource name="jdbc/databaseWeb" auth = "Container" type = "javax.sqlDataSource" maxActive = "100" maxIdle = "30" maxWait = "10000" username = "root" password = "admin" driverClassName = "com.mysql.jdbc.Diver" url = "jdbc:mysql://localhost:3306/databaseWeb?characterEncoding=utf8"></Context>
注意此時要把Mysql的驅動放到Tomcat全域的lib裡面
然後要在應用程式的web.xml中配置資料來源的應用:
<resource-ref> <description>DBConnection</description> <res-ref-name>jdbc/databaseWeb</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth></resource-ref>
在java檔案中使用資料來源:
Context initContext = new InitialContext();//擷取所有的資源Context envContext = initContext.lookup("java:/comp/env");擷取JNDI資源DataSource ds =(DataSource) envContext.lookup("jdbc/databaseWeb");//擷取資料庫連接Connection conn= ds.getConnection();