Eclipse工程目录META-INF/context.xml。
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/myposdb" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000" username="pos"
password="mypassword" driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb://localhost:3306/myposb?characterEncoding=utf-8" />
</Context>
工程目录WEB-INF/web.xml文件中添加。
<resource-ref>
<res-ref-name>jdbc/myposdb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
数据库连接工具类。
package leo.pos.server;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class JdbcManager {
private static Logger logger = LogManager.getLogger();
private static InitialContext context = null;
public static Connection getConnection() {
try {
context = new InitialContext();
DataSource ds = (DataSource) context.lookup("java:/comp/env/jdbc/myposdb");
Connection conn = ds.getConnection();
return conn;
} catch (NamingException e) {
logger.fatal("数据源配置错误。" + e.toString());
} catch (SQLException e) {
logger.fatal("数据库查询失败。" + e.toString());
}
return null;
}
public static void close(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logger.info("数据库Connction关闭异常。" + e.toString());
}
}
}
public static void close(PreparedStatement ps) {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
logger.info("数据库PreparedStatement关闭异常。" + e.toString());
}
}
}
public static void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.info("数据库ResultSet关闭异常。" + e.toString());
}
}
}
}