Issue
I want to create a new user for a MySQL database from NetBeans but I don't know the core code for it.
I've tried:
try {
String query = "CREATE USER = '?' @'localhost' IDENTIFIED BY = '?'; ";
con = DriverManager.getConnection(url, uname, pwd);
PreparedStatement pstmnt = con.prepareStatement(query);
pstmnt.setString(1, newUser[0]);
pstmnt.setString(2, newUser[3]);
pstmnt.execute();
pstmnt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
The output is:
java.sql.SQLException:
Parameter index out of range (1 > number of parameters, which is 0).
I know in MySQL you can create a new user using:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
Solution
TimSolo How To have Dynamic SQL in MySQL Stored Procedure states that After 5.0.13, in stored procedures, you can use
dynamic sql
Omesh MySQL CREATE USER with a variable? uses dynamic SQL to create a new user and grant privileges
my concoction uses
stored procedures + dynamic sql
to produce the following answer for creating a new user:
CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`(IN username VARCHAR(250), IN pwd VARCHAR (100))
BEGIN
SET @s = CONCAT('CREATE USER "',username,'"@"localhost" IDENTIFIED BY "',pwd,'"');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Answered By - Yeezus