C# MySql CREATE USER

守給你的承諾、 提交于 2019-12-20 04:17:28

问题


I was trying to make a registration statement with C#. Obviously I couldn't make it. I don't exactly know what the problem is. With that said here is a snippet:

MySqlConnection Connection = 
 new MySqlConnection("SERVER=localhost;UID=root;");
MySqlCommand Command = 
 new MySqlCommand("CREATE USER 'testuser'@'localhost' 
 IDENTIFIED BY 'superpassword';", Connection);
Command.ExecuteNonQuery();

回答1:


Before executing the command, you need to open the connection

using(MySqlConnection Connection = new MySqlConnection("SERVER=localhost;UID=root;"))
using(MySqlCommand Command = new MySqlCommand("CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'superpassword';", Connection))
{
    Connection.Open();
    Command.ExecuteNonQuery();
}

Do not forget to enclose the disposable commands in a Using Statement

EDIT Looking at your code (why don't you put here immediately?) it is clear where is the error

this line

this.COMMAND = String.Format("CREATE USER '{0}'@'{1}' IDENTIFIED BY '{3}';", username, host, password); 

should be

this.COMMAND = String.Format("CREATE USER '{0}'@'{1}' IDENTIFIED BY '{2}';", username, host, password); 

There are three parameters passed to the string format, so the indexes to be used for the placeholders in the string.format are 0, 1 and 2.
You used 3 for the password and this gives the out of range exception



来源:https://stackoverflow.com/questions/23460954/c-sharp-mysql-create-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!