使用java在mysql中创建用户
在以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'");
为什么insert命令有效但grant命令永远不能通过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();