MySQL连接池

    技术2022-05-20  89

    1:

    public class Basedao { //设计单例模式之初始化当前类的实例 private static Basedao dao; //private Basedao(){} //得到当前类的实例 public static synchronized Basedao getBasedao(){    if(dao==null){     dao=new Basedao();    }  return dao; } //获取数据库连接的方法    public static DataSource getDataSource(){      //初始化数据库源   DataSource ds=null; try {  Context initctx = new InitialContext();  Context envctx = (Context) initctx.lookup("java:comp/env");  //从Context中lookup数据源。        ds = (DataSource)envctx.lookup("jdbc/mytest"); } catch (Exception e) {  System.out.print("出错的信息:");  System.out.println(e); }   return ds;    }}

    2:jndi.properties

    java.naming.factory.initial=org.jnp.interfaces.NamingContextFactoryjava.naming.provider.url=jnp://localhost:8090

    3:context.xml         tomcat/conf/目录下

    <?xml version="1.0" encoding="UTF-8"?><Context path="/WebItem" docBase="webItem"    debug="5" crossContext="true" reloadable="true"    cachingAllowed="true" cacheMaxSize="20480"    cacheTTL="10000"><WatchedResource>WEB-INF/web.xml</WatchedResource><Resourcename="jdbc/mytest"auth="Container"type="javax.sql.DataSource"driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://localhost:3306/mytest?autoReconnect=true"username="root"password="root"maxActive="20"maxIdle="10"maxWait="-1" /></Context>

    4:web.xml

    <!--数据库连接池的配置--> <resource-ref>    <description>DB Connections</description>  <res-ref-name>jdbc/mytest</res-ref-name>  <res-type>javax.sql.DataSource</res-type>  <res-auth>Container</res-auth> </resource-ref>

    5:加个log4j吧

    log4j.rootLogger=info,stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayout# pattern to output thi Caller's file name and line number.log4j.appender.stdout.layout.ConversionPattern=%5p [%t] [%F:%L] - %m%n


    最新回复(0)