No suitable drivers found for jdbc mysql?

I am trying to write a program to connect to a MySQL database in eclipse, but I get the error message "java.sql.SQLException: no suitable driver was found".

Java code:

import java.sql.*;

public class FirstExample {

//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";  
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";

public static void main(String[] args) {

    try {

        System.out.println("Connecting to database...");
        //Class.forName(S_JDBC_DRIVER);
        Connection connection = DriverManager.getConnection(S_DB_URL,
                S_USER, S_PASS);

        System.out.println("Creating statement...");
        Statement statement = connection.createStatement();
        String sql = "SELECT * FROM Employee";
        ResultSet resultSet = statement.executeQuery(sql);

        while (resultSet.next()) {

            int iId = resultSet.getInt("id");
            int iAge = resultSet.getInt("age");
            String sFirst = resultSet.getString("fname");
            String sLast = resultSet.getString("lname");

            System.out.print("ID: " + iId);
            System.out.print("\tAge: " + iAge);
            System.out.print("\tFirst: " + sFirst);
            System.out.println("\tLast: " + sLast);
        }

        resultSet.close();
        statement.close();
        connection.close();
    } catch (SQLException se) {

        for (Throwable t : se) {
            t.printStackTrace();
        }
    } 
    System.out.println("Goodbye!");
}

}

The output on the console tab:

Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!

I used MySQL Connector / J. It is unpacked in the MySQL installation directory, and the jar file is added to CLASSPATH.

Also see this image. There is! mark in the project root image01

I get an error, as in the following image: image02 , when I include 2 comments:

static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
+5
source share
5 answers

, , CLASSPATH . Class-Path jar -cp java.

JDBC MySQL Eclipse.

+3

. , :

Class.forName("com.mysql.jdbc.Driver");
+4

java -cp pwd /mysql-connector-java-5.1.22-bin.jar:. <classname>.

, , mysql.

, .

+1

jar eclipse, eclipse, , " Java" β†’ "" β†’ jar mysql-connector-java.jar java mysql /usr/share/java/ ubuntu. "" . .

0

, , : , mysql-connector-java-5.1.23-bin.jar, \Apache Software Foundation\Tomcat 6.0\lib tomcat. ,

-1

All Articles