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/"
/>
模板仅供参考根据自己的需要自定义模板

1007

被折叠的 条评论
为什么被折叠?



