To connect to your MySQL database under Tomcat you can use the JDBC driver which is already included with our Tomcat instance.
You can use JDBC to connect to your MySQL. An example code is provided below:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/yourdatabase
userName=your_mysql_user
password=your_mysql_pass
Below is an example of a simple JSP code working with MySQL via JDBC:
<%@ page import="java.sql.*" %>
<%
String username="your_mysql_username";
String password="your_mysql_username_password";
String dbName="your_complete_database_name";
String dbHost="localhost";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException msg) {
out.println("Error loading driver:" + msg.getMessage());
}
try{
String url ="jdbc:mysql://"+dbHost+":3306/"+dbName;
Connection Conn = DriverManager.getConnection(url,username, password);
Statement Stmt = Conn.createStatement();
String query = "select now()";
ResultSet res = Stmt.executeQuery(query);
while(res.next())
{
out.println("Query result : "+res.getObject(1));
}
} catch(SQLException e) {
String err1Msg = e.getMessage();
%>
<TD COLSPAN="2"><STRONG><EM>err1Msg = <%= err1Msg %></EM></STRONG></TD>
<%
}
%>
Shared Tomcat clients: Please note that the MySQL connector is already loaded and you do not need to include that as an additional JAR
Private Tomcat (JVM) clients: Please note that the MySQL connector is NOT loaded by default and you need to add any necessary MySQL connectors to your instance in order for your site to connect to MySQL through JDBC