0

I am trying to establish a connection to a MySQL database to read and write data. However, I get an error when trying to run this code:

public void openConnection() throws SQLException {
  Class.forName("com.mysql.jdbc.Driver");
  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/jared_bookoo",                                          "root", "pass");
  Statement stmt = conn.createStatement();
}

The weird thing is, all my tests pass when I run a JUnit test. I am able to read from the database correctly and return the correct data. However, once I hook it up to a JSP and try to read it from a locally hosted webpage, I get the following error:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/jared_bookoo
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at jared.simpledatabase.DBInterface.openConnection(DBInterface.java:42)
    ...

What is happening, and how can I fix it? The driver is installed (and working; I can read from the database in my tests), so I don't see what could be going wrong.

Jared Nielsen
  • 3,669
  • 9
  • 25
  • 36

1 Answers1

2

Put the MySQL driver jar in your WEB-INF/lib library. You can find it here. Also, make sure that when you generate the war file, the MySQL driver jar is in web_app_name/WEB-INF/lib.

Another advice (just in case since you don't specify where you call that method): You should never try to use Java code directly in your JSP. For further info, refer to How to avoid Java code in JSP files?.

One more advice, in real world web applications, you would use a Data Source to get the Connection. Since you don't specify which application server you use, I'll let an example about configuring the Data Source in Tomcat 7.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • That did the trick. Thanks so much for your help! To clarify, the database connection code is not in the JSP; it's in its own separate class. I just only included the relevant stuff in my question. – Jared Nielsen Mar 26 '13 at 17:39
  • @jarednielsen I didn't said that you put the database connection code in your JSP, I just clarified that you shouldn't write any kind of Java code in your JSP i.e. scriptlets. – Luiggi Mendoza Mar 26 '13 at 19:09