81,094
社区成员
发帖
与我相关
我的任务
分享
<!-- appName 为项目名 --!>
<Context path="/appName" docBase="appName" auth="Container">
<Resource name="jdbc/MySQLDS" scope="Shareable"
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/test?useUnicode=true&charact-erEncoding=GBK"
driverClassName="com.mysql.jdbc.Driver"
username="root" password="111111"
maxWait="3000" maxIdle="100" maxActive="10" />
</Context>
<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>MySQLDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBUtil {
public Connection getConnection() throws Exception {
Context context = new InitialContext();
// 获取数据源
DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/MySQLDS");
// 获取数据库连接
Connection conn = ds.getConnection();
if (conn != null && !conn.isClosed()) {
return conn;
} else {
return null;
}
}
}