[英]Creating Registration form in c# with mysql
您好,我用MySql在C#中創建注冊表格,因此它連接到數據庫和所有內容,但我收到此錯誤Napaka pri registraciji
Unknown column " in 'field list'
中Napaka pri registraciji的翻譯意味着注冊時出錯,我只在其中擁有它我的語言。在文本框中插入數據並按注冊時,出現此錯誤。
編碼:
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中,“滴答”代表數據庫對象,因此查詢要查找由這些值命名的對象,而不是使用值本身。 所以代替這個:
`"+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);
然后,當您執行該命令時,它將把用戶輸入的值視為值,而不是可執行代碼 。
將值更改為單引號'
。
dataCommand.CommandText =
"Insert INTO lr.users (upIme,geslo)
VALUES ('"+this.tB_upIme.Text+"','"+this.tB_geslo.Text+"');";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.