【MySQL】JavaWeb项目中配置数据库的连接池

在META-INF目录下新建context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
    maxActive="10" maxIdle="4"
    username="root" password="" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/库名" />
</Context>

在DAO中获取连接实例

    public static Connection getConnect(){
        Context initContext;
        Context envContext;
        Connection con = null;
        try {
            initContext = new InitialContext();
            envContext = (Context) initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/PriceDB");
            con = ds.getConnection();
            System.out.println("数据库连接成功");
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return con;
    }

 

posted @ 2019-07-15 19:48  HanJunOvO  阅读(2327)  评论(0编辑  收藏  举报