0

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';
9
  • What is your question exactly? Based on this, your prepared statement syntax is wrong: docs.oracle.com/javase/7/docs/api/java/sql/… Commented May 19, 2017 at 7:16
  • do you want to create a new table in mysql using netbeans? Commented May 19, 2017 at 7:20
  • Have you at least tried this code? What is the output? Commented May 19, 2017 at 7:21
  • @AluanHaddad, I thought I'd use similar code Commented May 19, 2017 at 7:31
  • @geunhter Yes, I have Commented May 19, 2017 at 7:32

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.