C#MySql创建用户 [英] C# MySql CREATE USER

查看:155
本文介绍了C#MySql创建用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用C#制作注册声明.显然我做不到.我不完全知道问题是什么.上面说的是一个代码段:

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();

推荐答案

在执行命令之前,您需要打开连接

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();
}

不要忘记将一次性命令括在Using语句中

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.COMMAND = String.Format("CREATE USER '{0}'@'{1}' IDENTIFIED BY '{3}';", username, host, password); 

应该是

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

有三个参数传递给字符串格式,因此要用于字符串占位符的索引.格式为0、1和2.
您使用了3作为密码,这给出了超出范围的异常

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

这篇关于C#MySql创建用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆