Reputation: 3907
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.
Upvotes: 0
Views: 201
Reputation: 85789
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.
Upvotes: 2