MySQL JDBC and JSP

From Lunarpages Web Hosting Wiki

Jump to: navigation, search

How do I connect to MySQL from within my JSP or Java Servlet?

You will need to use JDBC to connect. A sample on how to connect to MySQL follows.

Make a handle to your database like this:

private static String driver = "com.mysql.jdbc.Driver";
/* its faster to use a relative path here instead... */
private static String url = "jdbc:mysql://www.yourAddress/yourUsername_yourDatabaseName";
private static String username = "yourUsername";
private static String password = "yourPassword";
Make a query like this:
String myDataField = null;
String myQuery = "SELECT * FROM yourTableName";
Connection myConnection = null;
PreparedStatement myPreparedStatement = null;
ResultSet myResultSet = null;
try {
Class.forName(driver).newInstance();
myConnection = DriverManager.getConnection(url,username,password);
myPreparedStatement = myConnection.prepareStatement(myQuery);
myResultSet = myPreparedStatement.executeQuery();
if(myResultSet.next())
myDataField = myResultSet.getString("myDataField");
}
catch (Exception myException)
{
System.out.println("database exception!");
myException.printStackTrace();
}

Want to read this in another language?

Lunarpages Deal: Save $72 on your next Business web hosting plan! Starting at $18.95 per month, this an offer you can't miss. Perfect for business and e-commerce hosting sites, comes with free e-commerce tools and a TremenDesk Help Desk. Limited time offer!