Reputation: 53
I have created java web application in eclipse with database mysql.But now i have to deploy that web application in tomcat server.I know how to deploy web application without databas but need assistance with database. Thank you in advance.
Upvotes: 3
Views: 10668
Reputation: 17940
There are 2 scenarios here:
Class.forName()
- in that case you just need to make sure the jar containing the driver is in the classpath and it should work.This is the preferred method - Define a Datasource on the server and call it in the code by using the JNDI API:
InitialContext ic = new InitialContext();
DataSource ds = (DataSource)ic.lookup("jdbc/testDS");
conn = ds.getConnection();
Upvotes: 1
Reputation: 94499
There are two main ways to obtain JDBC connections within a Java Web Application.
JNDI
Using JNDI requires a connection pool to be created within tomcat. This can be done within the context.xml file in tomcat's config
directory.
Example Context.xml Entry
<Resource name="jdbc/EmployeeDB"
auth="Container"
type="javax.sql.DataSource"
username="dbusername"
password="dbpassword"
driverClassName="org.hsql.jdbcDriver"
url="jdbc:HypersonicSQL:database"
maxActive="8"
maxIdle="4"/>
This connection would then be retrieved in your code as follows:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
Manual Creation
Manually creating the connection within your code is simpler, however JNDI is recommended for its portability.
Manual Example
public class MysqlConnect{
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When deploying for either of these scenarios it is important that you have the appropriate JDBC driver in your classpath.
Upvotes: 3