문제

In MySQL command line client after logging in as root, I typed:

connect mydb;
grant all privileges on mydb.* to 'admin'@'localhost' identified by 'pass';

Now within Java, I succesfully connect to the db using the admin userid using drivers.

 Statement put=connect.createStatement();

 //**WORKS succesfully**
 put.execute("insert into mydb.emp values(100,joe)");   

 //**does NOT work**
 put.execute("grant all privileges on mydb.* to 'john'@'localhost' identified by 'pass'"); 

Why does an insert command work but grant command never work through Java?

Please help.

도움이 되었습니까?

해결책

put.execute(MySQL query) 

in here you can execute only MySQL query but

grant all privileges on mydb.* to 'admin'@'localhost' identified by 'pass';

Not a MySQL query it is just a command for MySQL.

다른 팁

You just forgot the quotation marks.

Try following

put.execute("grant all privileges on mydb.* to 'john'@'localhost' identified by 'pass'"); 

And also make sure you have ExtendedAnsiSQL flag to 1.

I tried working with query parameters - what I found somewhat confusing is that you have to put a blank between the parameter and @localhost for example - this here worked for me: (jpaEm is a JpaEntityManager here)

// Create user
String sql = "CREATE USER ? @localhost";
Query query = jpaEm.createNativeQuery(sql);
query.setParameter(1, user.getUserName());
jpaEm.getTransaction().begin();
query.executeUpdate();
jpaEm.getTransaction().commit();

// Set password
sql = "SET PASSWORD FOR ? @localhost = PASSWORD(?)";
query = jpaEm.createNativeQuery(sql);
query.setParameter(1, user.getUserName()); 
query.setParameter(2, user.getPassword());
jpaEm.getTransaction().begin();
query.executeUpdate();
jpaEm.getTransaction().commit();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top