在META-INF目录下新建context.xml文件:
<Context>
<Resource name="jdbc/mydb" auth="Container"
type="javax.sql.DataSource"
maxActive="200"
maxIdel="50"
maxWait="3000"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8"
>
</Resource>
</Context>
使用:
javax.naming.Context context = new javax.naming.InitialContext();
javax.sql.DataSource ds = (DataSource)context.lookup("java:/comp/env/jdbc/mydb");
Connection conn = ds.getConnection();
String sql = "select * from mytable";
PreparedStatement pstmt = conn.preparedStatement(sql);
ResultSet rs = pstmt.executeQuery();