I am a new programmer with BlueJ I had to create a class called Connexion
which connects to my MySQL database, but I get this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
My Code:
import java.sql.* ;
public class Connexion{
/**
* Connect to MySQL and read the table "Etat", then
* print the contents of the first column.
*/
public static void test()
{
try
{
// Load the database driver
Class.forName( "com.mysql.jdbc.Driver" ) ;
// Get a connection to the database
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/OACA?user=root&password=" ) ;
// Print all warnings
for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
{
System.out.println( "SQL Warning:" ) ;
System.out.println( "State : " + warn.getSQLState() ) ;
System.out.println( "Message: " + warn.getMessage() ) ;
System.out.println( "Error : " + warn.getErrorCode() ) ;
}
// Get a statement from the connection
Statement stmt = conn.createStatement() ;
// Execute the query
ResultSet rs = stmt.executeQuery( "SELECT * FROM Etat" ) ;
// Loop through the result set
while( rs.next() )
System.out.println( rs.getString(1) ) ;
// Close the result set, statement and the connection
rs.close() ;
stmt.close() ;
conn.close() ;
}
catch( SQLException se )
{
System.out.println( "SQL Exception:" ) ;
// Loop through the SQL Exceptions
while( se != null )
{
System.out.println( "State : " + se.getSQLState() ) ;
System.out.println( "Message: " + se.getMessage() ) ;
System.out.println( "Error : " + se.getErrorCode() ) ;
se = se.getNextException() ;
}
}
catch( Exception e )
{
System.out.println( e ) ;
}
}
public static void main(String[] args) {
test();
}
}
So how can I connect to my MySQL v5.6.17 database that is in my Wampserver. I think that I need a coonector.jar But I don't know which one that I would actually need. Can you give your opinion please?
You probably need to include the driver in the classpath. If you're using maven, add the driver as a dependency in your pom.xml file
something like this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
If you're not using maven, try the solution proposed in this question:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse