MySQL / JDBC connection Print

  • 0

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

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://YOUR_DB_SERVER_NAME/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="YOUR_DB_SERVER_NAME";
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>
<%
}
%>


Was this answer helpful?

« Back