1

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();
user353gre3
  • 2,747
  • 4
  • 24
  • 27
isastim
  • 13
  • 1
  • 5
  • What error do you get from this command? – drew_w May 04 '14 at 20:03
  • Ouh that's hard to say. My exception-message outputs in german. I'll try to translate: The Index based on 0(null) must be greater or equal Null and less than the size of the argumentlist. – isastim May 04 '14 at 20:20

1 Answers1

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

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Oh, sorry almost forgot that. thanks ;) But I still have the problem. Connection.Open(); didn't fix it :( I close my connection with if(Connection.State == ConnectionState.Open){ Connection.Close();} But I think it does pretty the same :) – isastim May 04 '14 at 20:15
  • What is the error message? It is raised on the Command.ExecuteNonQuery line?. I have tested the same code here and I don't have any error here – Steve May 04 '14 at 20:38
  • Do I need to specify it if I just want to Create a MySql-User? If I type this command into PHPMyAdmin without selecting a certain Database it creates a new user without problems. – isastim May 04 '14 at 20:38
  • No, I tested it and you don't need it – Steve May 04 '14 at 20:46
  • See here to see a more detailed snippet. I made a Class which has some basic MySql functions....so don't wonder ^_^ http://pastebin.com/1YQLT9cJ Thanks for your support. – isastim May 04 '14 at 20:49
  • Ohh...I think I don't need to explain how dump I feel in this situation.... >.< However, and It finally works now thanks to you sir :) – isastim May 04 '14 at 20:54