0

我目前使用 Intellij,事实证明我正在尝试连接到 MySQL 数据库,但是在添加库并使用与 MariaDB 驱动程序完美配合的连接类之后,我发现问题标题中的错误

public void conectar() {
        try {
            conexion = DriverManager.getConnection(url, usuario, contraseña);
            if (conexion != null) { JOptionPane.showMessageDialog(null, "Conexión establecida a : \n" + url,  "ACDA2", JOptionPane.INFORMATION_MESSAGE);
                Class.forName("com.mysql.jdbc.Driver");
                stm = conexion.createStatement();//crea un objeto que permite enviar instrucciones a la base de datos
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Conexión fallida a : \n " + url, "", JOptionPane.ERROR_MESSAGE);
            System.out.println(ex.getMessage());
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(null, "Error al cargar el driver", "", JOptionPane.ERROR_MESSAGE);
            System.out.println(e.getMessage());
        }
    }

在此处输入图像描述

在此处输入图像描述

这些是我发送到我的班级连接的值

c= new conexion("jdbc:mysql://", "127.0.0.1/", "root", "", "sanciones"); c.conectar();

然后我详细介绍了连接类构造函数

 public conexion(String driver,String host, String usuario, String 
 contraseña, String baseDatos) {
    this.usuario = usuario;
    this.contraseña = contraseña;
    this.baseDatos = baseDatos;
    this.driver = driver;
    this.host = host;
    this.url = driver + this.host  + this.baseDatos;
}

更新

驱动版本 com.mysql.jdbc_5.1.5 不允许隐式加载驱动,因为 META-INF 中缺少 Services 子文件夹及其对应的内容,即使是 JDBC4,在 mysql 手册中都说有可能,至少在这个特定版本中不是,问候

4

2 回答 2

0

需要先调用“Class.forName”才能加载正确的驱动程序。试试这个,

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conexion = DriverManager.getConnection(url, usuario, contraseña);
        if (conexion != null) { JOptionPane.showMessageDialog(null, "Conexión establecida a : \n" + url,  "ACDA2", JOptionPane.INFORMATION_MESSAGE);
            stm = conexion.createStatement();//crea un objeto que permite enviar instrucciones a la base de datos
        }
于 2018-11-10T14:13:10.657 回答
0

Class.forName 应该在获得连接之前被调用

于 2018-11-10T14:05:21.927 回答