IDEA2020配置Tomcat数据源

IDEA配置Tomcat数据源

首先需要配置context.xml

一.
步骤!

二.
步骤二

步骤三
四.

步骤四

步骤五

步骤六

步骤七

步骤八
xml内容

<Resource
            name="pool"
            auth="Container"
            type="javax.sql.DataSource"
            maxActive="100"
            maxIdle="30"
            maxWait="10000"
            username="root"
            password="root"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/"
    />

修改连接数据库部分(BaseDao)

修改前

   //加载驱动
    private static final String DRIVER_URL = "com.mysql.cj.jdbc.Driver";
    //数据库地址
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/?user=root&password=root&useSSL=false&map&severTimezone=UTC";

    static {
        try {
            //加载驱动
            Class.forName(DRIVER_URL);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接数据库
     *
     * @return connection
     */
    public static Connection getConnection() {
        Connection connection = null;
//        创建连接
        try {
            connection = DriverManager.getConnection(JDBC_URL);
            //获得连接
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回连接
        return connection;
    }

修改后

  static Connection conn = null;
    static PreparedStatement pstmt = null;
    static ResultSet rs = null;
    private static DataSource dataSource = null;
    static {
        try {
            Context initCtx=new InitialContext();
            Context envCtx=(Context) initCtx.lookup("java:comp/env");
            dataSource=(DataSource) envCtx.lookup("pool");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
    //1.连接获得公共的连接静态方法
    public static Connection getConnection() {
        try {
            conn =dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

只需要改变静态代码块和getConnection()的内容即可
导入连接数据库的jar包就可以运行了

如果觉得每次都需要写context.xml部分麻烦可以定义好模板
在这里插入图片描述
在这里插入图片描述
将配置好的模板写入即可

<Resource
            name="pool"
            auth="Container"
            type="javax.sql.DataSource"
            maxActive="100"
            maxIdle="30"
            maxWait="10000"
            username="root"
            password="root"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/"
    />

模板仅供参考根据自己的需要自定义模板

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值