creating user in mysql using java

喜你入骨 提交于 2019-12-02 11:35:12
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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!