MySQL Java Database Connect Demo
The code below is to help you get started. Copy the code into your
subdirectory in the servlet zone and compile it there. You will need to
change the
'xxxxxx' of "con = DriverManager.getConnection (url, db,"xxxxxx");"
to reflect your MySQL password and the 'package db;' to reflect your
subdirectory name. Copy the HTML form above to
your public_html directory and use it connect to
your database via the servlet code. Replace the 'test418' with your
database name and the URL with your servlet URL.
package db;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ConnMySQL extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String db = req.getParameter("db");
String user = db; // assumes username is same as db name
String url="jdbc:mysql://localhost/"+db;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String query;
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
try {
//Load the driver
Class.forName("org.gjt.mm.mysql.Driver");
//Get a Connection to the database
con = DriverManager.getConnection (url,user,"xxxxxx");
out.println("<HTML><HEAD><TITLE>JDBC Connect Demo</TITLE></HEAD>");
out.println("<BODY><h2>JDBC Connect Demo</h2>");
out.println("<h4>Database " + db+" Opened</h4>");
} // end try
catch(ClassNotFoundException e) {
out.println("Could not load database driver: " +e.getMessage());
}
catch(SQLException e) {
out.println("SQLException caught: " +e.getMessage());
}
finally {
//close the database connection.
try {
if (con != null) con.close();
}
catch (SQLException e) {}
}
}
}