一尘不染

找不到适合jdbc mysql的驱动程序?

mysql

我正在尝试编写一个程序以在eclipse中连接到MySQL数据库,但出现错误 “ java.sql.SQLException:找不到合适的驱动程序”

Java代码是:

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!");
}

}

控制台选项卡中的输出为:

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!

我已经使用了MySQL Connector / J。将其解压缩到MySQL安装目录中,并将jar文件添加到CLASSPATH中。

另请参阅此图像。有一个
!在项目根目录上标记。image01

当我包含2条注释语句时,出现下图所示的错误:image02

static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);

阅读 442

收藏
2020-05-17

共1个答案

一尘不染

除了最琐碎的应用程序之外,所有其他应用程序CLASSPATH不会 使用环境变量。通常,这些库包含在Class- Pathjar清单的条目中,或者-cp包含在Java命令行的选项中。

在这种情况下,您需要将MySQL JDBC驱动程序添加到Eclipse项目的buildpath中。

2020-05-17