如何创建用户和授予权限MySql

时间:2015-04-15 06:05:32

标签: c# mysql

我正在尝试在MySql数据库上创建一个新用户,并授予他们仅查看权限,以便他们可以环顾四周,实际上无法更改任何内容。我尝试过以下代码:

string query = "INSERT INTO users(user_name, password, admin) VALUES('" + usernameTextBox.Text + "','" + passwordTextBox.Text + "', '1')";
MySqlCommand command = new MySqlCommand(query, databaseConnection);
command.ExecuteNonQuery();


query = "CREATE USER '" + usernameTextBox.Text + "' IDENTIFIED BY '" + passwordTextBox.Text + "'";
command = new MySqlCommand(query, databaseConnection);
command.ExecuteNonQuery();

query = "GRANT SELECT, SHOW DATABASES ON database.* TO '" + usernameTextBox.Text + "'@'%'";
command = new MySqlCommand(query, databaseConnection);
command.ExecuteNonQuery();

我收到以下错误:

  

DB GRANT和GLOBAL PRIVILEGES

的使用不正确

我一直在尝试阅读MySql的文档并在Stack Overflow上阅读其他问题,但我似乎无法弄明白

2 个答案:

答案 0 :(得分:0)

CREATE USER,FILE,PROCESS,RELOAD,REPLICATION CLIENT,REPLICATION SLAVE, SHOW DATABASES ,SHUTDOWN和SUPER权限是管理权限,只能全局授予。 无法应用于单个数据库 你需要拆分拨款查询

GRANT SHOW DATABASES ON *.* TO 'username'@'%'; -- GRANT TO ALL DATABASES
GRANT SELECT ON database.*  TO 'username'@'%';

P.S。并且您的代码对于SQL注入不安全,您必须使用prepared statements

答案 1 :(得分:0)

授予 MySQL 或MariaDB

的权限

GRANT ALL PRIVILEGES ON DatabaseName.* TO 'username'@'%' WITH GRANT OPTION;