<TOMCAT_HOME>/lib/mysql-connector-java-5.1.38-bin.jar
Create Global Resource in Context
<TOMCAT_HOME>/conf/context.xml
Code: Select all
<Context>
...
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="dbusername" password="dbpassword" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://192.168.1.2:3306/MyDbName"/>
</Context>
In the project, create a reference to the Resource:
webapps/<PROJECT_DIR>/WEN_INF/web.xml
Code: Select all
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<servlet>
...
</servlet>
<servlet-mapping>
...
</servlet-mapping>
...
</web-app>
In the JAVA code:
Code: Select all
public class DbHelper {
private DbHelper() throws SQLException, ClassNotFoundException {
String dataResourceName = "jdbc/TestDB";
try {
Context initialContext = new InitialContext();
Context environmentContext = (Context) initialContext.lookup("java:comp/env");
DataSource dataSource = (DataSource) environmentContext.lookup(dataResourceName);
connect = dataSource.getConnection();
} catch(NamingException e) {
logger.error("DbHelper Naming exception:" + e);
}
}
try {
String insertQuery = "delete from " + db_table + " WHERE id=?";
preparedStatement = connect.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setInt(1,record_id ); // id auto increment
preparedStatement.executeUpdate();
logger.info("query:" + preparedStatement.toString() );
return true;
} catch (SQLException e) {
logger.error("Error for query:" + e);
logger.error("Error query:" + preparedStatement.toString());
return false;
}