Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用mysql在c#中创建注册表_C#_Mysql - Fatal编程技术网

使用mysql在c#中创建注册表

使用mysql在c#中创建注册表,c#,mysql,C#,Mysql,您好,我正在用MySql在C#中创建一个注册表单,这样它就可以连接到数据库和所有东西,但是我得到了这个错误Napaka pri registiciji未知列“在‘字段列表’中,Napaka pri registraciji的翻译意味着注册时出错,我只是用了我的语言。我在文本框中插入数据并按Register时出现此错误 守则: private void btn_Reg_Click(object sender, EventArgs e) { MySqlConnection d

您好,我正在用MySql在C#中创建一个注册表单,这样它就可以连接到数据库和所有东西,但是我得到了这个错误
Napaka pri registiciji
未知列“在‘字段列表’
中,Napaka pri registraciji的翻译意味着注册时出错,我只是用了我的语言。我在文本框中插入数据并按Register时出现此错误

守则:

private void btn_Reg_Click(object sender, EventArgs e)
    {
        MySqlConnection dataConnection = new MySqlConnection();
        dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
        dataConnection.Open();
        MySqlTransaction transakcija = dataConnection.BeginTransaction();
        MySqlCommand dataCommand = new MySqlCommand();
        dataCommand.Connection = dataConnection;
        dataCommand.Transaction = transakcija;
        try
        {
            dataCommand.CommandText = "Insert INTO lr.users (upIme,geslo) VALUES (`"+this.tB_upIme.Text+"`,`"+this.tB_geslo.Text+"`)";
            dataCommand.CommandType = CommandType.Text;
            dataCommand.ExecuteNonQuery();
            transakcija.Commit();
            MessageBox.Show("Registracija uspešna!");
        }
        catch (Exception eks)
        {
            transakcija.Rollback();
            MessageBox.Show("Napaka pri registraciji\n" + eks.Message);
        }
        finally
        {
            dataCommand.Connection.Close();
        }
    }

在值中更改为单引号

dataCommand.CommandText = 
"Insert INTO lr.users (upIme,geslo) 
VALUES ('"+this.tB_upIme.Text+"','"+this.tB_geslo.Text+"');";

有两件事我马上就发现不对

首先,您使用反勾号来包装您的值。在MySQL中,回标记表示数据库对象,因此查询将查找由这些值命名的对象,而不是使用这些值本身。因此,与此相反:

`"+this.tB_upIme.Text+"`
你会想要这个:

'"+this.tB_upIme.Text+"'
其次,也是非常重要的一点,您的代码对SQL注入攻击非常开放。您需要使用查询参数,而不是直接字符串连接。虽然看起来您只是在向查询字符串中输入值,但实际上您是在接受用户输入并将其作为查询字符串中的可执行代码处理,这意味着用户可以在数据库中运行他们想要的任意代码

首先,向查询中添加参数:

"Insert INTO lr.users (upIme,geslo) VALUES (@upIme, @geslo)"
(您会注意到,这也使查询更清晰、更易于阅读。)然后将您的参数添加到命令中:

dataCommand.Parameters.AddWithValue("@upIme", this.tB_upIme.Text);
dataCommand.Parameters.AddWithValue("@geslo", this.tB_geslo.Text);

然后,当你执行该命令时,它将把用户输入值当作值而不是可执行代码。

注解的好注解。如果你的代码有用户输入,你的代码也不安全,你也应该考虑戴维的注释。