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

标签 c# mysql

你好,我正在使用 MySql 在 C# 中创建注册表单,以便它连接到数据库和所有内容,但我收到此错误 Napaka pri registraciji Unknown column "in 'field list' Napaka pri registraciji 的翻译意思是 Error at registering 我只是用我的语言。当我在文本框中插入数据并按 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();
        }
    }

最佳答案

这里有两点我立即看出错误...

首先,您使用反引号来包装您的值。在 MySQL 中,Back ticks 代表数据库对象,因此查询正在寻找由这些值命名的对象,而不是使用这些值本身。所以不是这个:

`"+this.tB_upIme.Text+"`

你会想要这个:

'"+this.tB_upIme.Text+"'

其次,更重要的是,您的代码对 SQL 注入(inject)攻击完全开放。您需要使用查询参数,而不是直接的字符串连接。虽然看起来您只是将值放入查询字符串中,但您实际上是在获取用户输入并将其视为查询字符串中的可执行代码,这意味着用户可以运行他们可以运行的任意代码想要在您的数据库上。

首先,向您的查询添加参数:

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

然后,当您执行该命令时,它将把用户输入的值视为,而不是可执行代码

关于c# - 使用 mysql 在 c# 中创建注册表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22227300/

相关文章:

c# - 我们如何利用单元/测试类文件中所有文件共享的通用方法(例如登录方法)?

mysql - 将 Spark 和 Mysql 与 mysql-connector-java 结合使用

mysql - 如何在 MySQL ORDER BY 语句中将 'empty' ,0,NULL 视为相同

PHP 选择特定行

c# - RemotePresenceView 只收到一个通知,然后就什么都没有发生

c# - ASP.NET C# - 从 Outlook Live SMTP 服务器发送电子邮件

c# - 如何从 MSBuild 代码分析中获取 XML 报告

c# - 带有引用类型参数的 ref 关键字

MySQL #1025 错误

c++ - Mysql 与 C++ 不工作