如何用java程序创建mysql用户

dgtucam1  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(234)

我正在从github respository升级到java应用程序。我想用户将在mysql数据库中创建。当我尝试运行这个示例时,它总是显示“java.sql.sqlexception:access denied for user'user'@'localhost'(using password:yes)”错误。我想是我的数据库设置错误造成的。我错了?
创建用户代码:

public SignIn(String password, String login) throws SQLException {
    DBConnect dao2 = new DBConnect("root", "");
    String sql = "SET old_passwords=0";
    String sql2 = "CREATE USER IF NOT exists ? @'localhost'";
    String sql3 = "SET PASSWORD FOR ? @localhost = PASSWORD(?)";
    PreparedStatement pst = dao2.getCon().prepareStatement(sql);
    pst.execute();
    dao2.getCon().commit();
    pst = dao2.getCon().prepareStatement(sql2);
    pst.setString(1,login);
    pst.execute();
    dao2.getCon().commit();
    pst = dao2.getCon().prepareStatement(sql3);
    pst.setString(1,login);
    pst.setString(2,password);
    pst.execute();
    dao2.getCon().commit();
    pst.close();
    gettingStart(dao2, login,password);
    dao2 = null;
}

以及自动化:

private void gettingStart(DBConnect dao ,String login, String password) throws SQLException {
    String sql1 = "CREATE SCHEMA IF NOT EXISTS bank";
    String sql2 = "CREATE TABLE IF NOT EXISTS bank.klienci (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), fname VARCHAR(50), number VARCHAR(50), balance DOUBLE, login VARCHAR(50))";
    String sql3 = "CREATE TABLE IF NOT EXISTS bank.actions (id INT AUTO_INCREMENT PRIMARY KEY, action_name VARCHAR(50), client_id INT, date DATETIME)";
    String sql4 = "CREATE TABLE IF NOT EXISTS bank.recipers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), fname VARCHAR(50), number VARCHAR(50),id_uzytkownika INT)";
    String sql5 = "GRANT ALL PRIVILEGES ON bank.klienci TO ? @'localhost' IDENTIFIED BY ?";
    String sql6 = "GRANT INSERT ON bank.actions TO ? @'localhost' IDENTIFIED BY ?";
    String sql7 = "GRANT ALL PRIVILEGES ON bank.recipers TO ? @'localhost' IDENTIFIED BY ?";
    PreparedStatement pst;
    pst = dao.getCon().prepareStatement(sql1);
    pst.execute();
    dao.getCon().commit();
    pst = dao.getCon().prepareStatement(sql2);
    pst.execute();
    dao.getCon().commit();
    pst = dao.getCon().prepareStatement(sql3);
    pst.execute();
    dao.getCon().commit();
    pst = dao.getCon().prepareStatement(sql4);
    pst.execute();
    dao.getCon().commit();
    pst = dao.getCon().prepareStatement(sql5);
    pst.setString(1,login);
    pst.setString(2,password);
    pst.execute();
    dao.getCon().commit();
    pst = dao.getCon().prepareStatement(sql6);
    pst.setString(1,login);
    pst.setString(2,password);
    pst.execute();
    dao.getCon().commit();
    pst = dao.getCon().prepareStatement(sql7);
    pst.setString(1,login);
    pst.setString(2,password);
    pst.execute();
    dao.getCon().commit();
    pst.close();
    System.out.println("Getting Started Done !");
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题