连接 Mysql 和 eclipse

Connecting Mysql and eclipse

我正在尝试连接到托管在 phpMyAdmin 和 Eclipse 上的 MySQL 数据库。我已经将 JDBC bin 文件导入到包中,并且我正在通过 XAMPP 访问 phpMyAdmin。这是代码:

import java.sql.Connection;
import java.sql.DriverManager;

public class database {
  public static void main(String[] args) {

    try {
       Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
       System.out.println("Connection successful");
    } catch (Exception e) {
       System.err.println(e);
    }
  }
}

但是当我编译它时,它说:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test'

这是什么意思?我正在观看一个 youtube 教程,它做的事情完全相同,但已经建立了连接。

先注册您的驱动程序:

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

您的代码应该是:

 try {
       Class.forName("com.mysql.jdbc.Driver");
       Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost/test","root","");
       System.out.println("Connection successful");
 } catch (Exception e) {
       System.err.println(e);
 }

尝试在创建连接之前添加:

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

我不确定你是否必须调用 newInstance() 方法,但它不会造成任何伤害。

注意:您必须下载并在构建路径中包含一个 mysql 连接器 jar,例如mysql-connector-java-5.1.14-bin.jar