繁体   English   中英

使用Java在mysql中创建用户

[英]creating user in mysql using java

以root用户身份登录后,在MySQL命令行客户端中键入:

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

现在在Java中 ,我使用驱动程序使用admin userid成功连接到数据库。

 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'"); 

为什么插入命令可以工作,但授予命令却不能通过Java工作?

请帮忙。

put.execute(MySQL query) 

在这里,您只能执行MySQL查询,但

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

不是MySQL查询,它只是MySQL的命令。

您只是忘记了引号。

尝试跟随

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

还要确保将ExtendedAnsiSQL标志设置为1。

我尝试使用查询参数-我发现有些困惑,例如您必须在参数和@localhost之间放置一个空格-这对我有用:(jpaEm在这里是JpaEntityManager)

// 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM