jndi方式创建数据源

通过jndi方式获取数据源,写了一个小例子 如下:

1、首先配置应用服务器,应用服务器我用的tomcat6.0,修改tomcat的conf目录下context.xml,在<WatchedResource>WEB-INF/web.xml</WatchedResource>下面配置如下(mysql数据库):

 <Resource name="jdbc/movie" auth="Container" type="javax.sql.DataSource"

    maxActive="200"

    maxIdle="100"

    maxWait="10000"

    username="root"

    password="root"

    driverClassName="com.mysql.jdbc.Driver"

    url="jdbc:mysql://127.0.0.1:3306/movie"/>  这里数据库的名称为movie,字段包括id和name varchar类型。

2、项目中web.xml的配置如下(原有基础上添加):

        <resource-ref>  

  <res-ref-name>jdbc/movie</res-ref-name>  

  <res-type>javax.sql.DataSource</res-type>  

  <res-auth>Container</res-auth>  

</resource-ref> 

3、获取数据库连接的方法:

import javax.naming.Context;

import javax.naming.InitialContext;

public static Connection getConnection(){

Connection conn = null;

try {

Context context = new InitialContext();

DataSource ds = (DataSource)context.lookup("java:/comp/env/jdbc/movie");

conn = ds.getConnection();

} catch (Exception e) {

e.printStackTrace();

}

return conn;

}

4、用的jar包:

commons-collections.jar

commons-dbcp.jar

commons-pool.jar

mysql-connector-java-5.1.7-bin.jar

猜你喜欢

转载自87430997.iteye.com/blog/1770486