JSP Hosting
 

HostingServicesSupportOrderAbout UsSoftwareHome


Even experts read the manuals. Our tech support staff has most of the books that are out on a wide variety of web topics. Here are some of their top picks. We think you'll find them useful and informative as well.



Accessing MySQL from Servlets

Java Database Connectivity (JDBC) allows servlets to lookup data and generate dynamic HTML output on the fly. MMA includes the org.mm.mysql.Driver class which allows you to connect to and query tables in your MySQL database. If you want to try the following example with your account, you will need to create a table called "test" in your MySQL database. The definition for the "test" table can be seen here.

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;
import java.sql.*;


// MyServlet.java



public class MyServlet extends HttpServlet
{ 

 public void doGet ( HttpServletRequest req, HttpServletResponse res ) 
 throws ServletException, IOException { 
  Connection con = null;
  Statement stmt = null;
  ResultSet rs = null;
  res.setContentType( "text/html"); 
  PrintWriter out = res.getWriter(); 
  out.println( "<html><body>" ); 
  try {
   Class.forName("org.gjt.mm.mysql.Driver");
   con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdbname",
    "username","password");
   stmt = con.createStatement();
   rs = stmt.executeQuery("select * from test");   
   while (rs.next()) {
    out.println("<LI> " + rs.getString("name") + " " + 
rs.getString("address") + " " + rs.getString("city") +
" " + rs.getString("phone")); } rs.close(); con.close(); } catch (Exception e) { } out.close(); } }

In a similar manner, you could add a doPost() method for inserting data into the database through a JDBC query.

For more information about accessing databases from Java, see the Java JDBC Tutorial.

Important: Mysql JDBC connections will automatically timeout after several hours. If you open a Mysql connection, don't expect it to stay open indefinitely. If Tomcat attempts to use a timed-out connection, you will get NullPointerException errors or your Tomcat might crash. Instead, you will need to use a database pool manager.

 

Note: MMA technical support staff cannot provide troubleshooting of problems with third-party CGI scripts including but not limited to: Perl scripts, C/C++ binaries, PHP or web/database integration unless these services are specifically contracted. For these services, please see our Quote Request Form.



Copyright © 1995-2012
Motivational Marketing Associates, LLC
All Rights Reserved.