To connect to DB using JNDI you have to perform the following steps:
Let’s do it step-by-step:
1. Create environment with database (MySQL in our case):
2. Create a new user in a database:How to create new user – click here
Database name : cirrusgridDb User_name : cirrusgrid Password : cirrusgrid
3. Modify configuration files in your web-application:context.xml:
<Context antiJARLocking="true" path="/JNDI"> <Resource name="jdbc/cirrusgridDb" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="cirrusgrid" password="cirrusgrid" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://mysql-jndi-example.qloud.asia/cirrusgridDb"/> </Context>
web.xml:
<resource-ref> <description>MySQL Datasource example</description> <res-ref-name>jdbc/cirrusgridDb</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
4. Create connection in java-class
public class MyConnection { private DataSource dataSource; public MyConnection() { try { InitialContext context = new InitialContext(); dataSource = (DataSource) context.lookup("java:comp/env/jdbc/cirrusgridDb"); } catch (NamingException ex) { Logger.getLogger(MyConnection.class.getName()).log(Level.SEVERE, null, ex); } } public Connection getConnection() { Connection conn = null; try { conn = dataSource.getConnection(); } catch (SQLException ex) { Logger.getLogger(MyConnection.class.getName()).log(Level.SEVERE, null, ex); } return conn; } }
Powered by BetterDocs
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.