Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

eclipse - No suitable driver found for jdbc mysql?

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

The java code is:

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("Age: " + iAge);
            System.out.print("First: " + sFirst);
            System.out.println("Last: " + sLast);
        }

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

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

}

The output in the console tab is:

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 have used the MySQL Connector/J. It is unzipped in the MySQL installation directory and the jar file is added to the CLASSPATH.

Also refer to this image. There is an ! mark at the project root.image01

I get the error as in the next image: image02 when I include the 2 commented statements:

static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same problem. I solved it by adding:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...