Servlet报错Access denied for user ‘root‘@‘localhost‘ (using password: YES),但mysql在非Servlet下正常

该代码段展示了如何使用Java连接到MySQL数据库,初始版本依赖于config.properties文件存储数据库信息。优化后,数据库凭据直接在代码中硬编码。连接过程涉及Class.forName()方法加载驱动,以及使用DriverManager.getConnection()建立连接。
摘要由CSDN通过智能技术生成

可能使用了config.properties保存、获取数据库信息导致


public class Connecter {
    private static String DBName;
    private static String acc;
    private static String pwd;
    public static Connection connectDB() {
        Connection con = null;
        getProperties();
        //System.out.println(DBName + acc + pwd);
        String url = "jdbc:mysql://localhost:3306/"+DBName+
                "?useSSL=true&&serverTimezone=UTC&characterEncoding=UTF-8";
        
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch(Exception e) {
            System.out.println("DB Driver loading failed");
        }
        
        try {
            con = DriverManager.getConnection(url, acc, pwd);
        }catch(SQLException e) {
            System.out.println(e + "\nDB connection failed");
        }
        
        return con;
    }
    
    public static void getProperties() {
        Properties properties = new Properties();
        File file = new File("./config.properties");
        if (!file.exists()) {
            try {
                file.createNewFile();
                FileWriter write = new FileWriter(file);
                write.write("DBName=shopstore\nacc=root\npwd=admin\n");
                write.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        DBName = properties.getProperty("DBName");
        acc = properties.getProperty("acc");
        pwd = properties.getProperty("pwd");
    }
}

改用以下即可


public class Connecter {
    private static String DBName = "****";
    private static String acc = "***";
    private static String pwd = "***";
    public static Connection connectDB() {
        Connection con = null;
        //System.out.println(DBName + acc + pwd);
        String url = "jdbc:mysql://localhost:3306/"+DBName+
                "?useSSL=true&&serverTimezone=UTC&characterEncoding=UTF-8";
        
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch(Exception e) {
            System.out.println("DB Driver loading failed");
        }
        
        try {
            con = DriverManager.getConnection(url, acc, pwd);
        }catch(SQLException e) {
            System.out.println(e + "\nDB connection failed");
        }
        
        return con;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值