与MySQL的连接

问题描述 投票:0回答:1

我正在尝试创建与数据库 mySQL 的连接,但它会导致不同的错误:


public class DBConfig {
    private String url;
    private String usuario;
    private String senha;
    private String database;


    public DBConfig(){
        try (FileInputStream fs = new FileInputStream("src/utils/db.properties")){
            Properties properties = new Properties();
            properties.load(fs);
            this.url = properties.getProperty("url");
            this.usuario = properties.getProperty("user");
            this.senha = properties.getProperty("password");
            this.database = properties.getProperty("database");
        } catch (IOException erro) {
            System.out.println(erro.getMessage());
        }
    }

...


import aulas.conexao.db.DBConfig;

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

public class Program {
    public static void main(String[] args) {
        DBConfig db = new DBConfig();
        Connection con = null;
        try {
            con = DriverManager.getConnection(db.getUrl()
                    ,db.getUsuario()
                    , db.getSenha());
            System.out.println("Conexão realizada com sucesso!");
            con.close();
        } catch (SQLException e) {
            try{
                System.out.println(e.getMessage());
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "123456789");
                System.out.println("conexão realizada com sucesso!");
                con.close();
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
}


第一次尝试阻止会导致用户“root”@“localhost”(使用密码:YES)访问被拒绝错误。即使参数与第一个相同,第二个 try 块也能工作。

我已经尝试了 YouTube 上的所有解决方案、文章,但没有解决问题。

java mysql properties database-connection
1个回答
0
投票

谁用用户、url 和密码初始化 DBConfig 对象 db?”

© www.soinside.com 2019 - 2024. All rights reserved.