使用参数化更新命令更新多个mysql列

时间:2014-11-04 14:03:18

标签: c# mysql sql-update parameterized-query

在我的应用程序中,我想使用 UPDATE 命令更新多个MySQL列。我尝试使用以下代码,但我知道它真的不安全。因为它导致了SQL注入攻击。但我不知道如何编写带参数的查询来更新多个MySQL列。

这是我的代码:

string constring = string.Format("datasource='{0}';port='{1}';database='{2}';username=claimsprologin;password=xxxxxxxxxxxxxxxx;Connect Timeout=180;Command Timeout=180", serveriplable.Text, portno.Text, databasenamelable.Text);
string Query = "update claimloans set loannumber= '" + this.loannumbertextbox.Text.Trim() + " ', pool = '" + this.loanpooltextbox.Text.Trim() + "' , disblid = '" + this.disbidtextbox.Text.Trim() + "' , category = '" + this.categorytxtbox.Text.Trim() + " ', subcacategory = '" + this.subcategorytxtbox.Text.Trim() + " ', invoice = '" + this.invoicenumbertextbox.Text.Trim() + " ', invoicedate = '" + this.invoicedatetextbox.Text.Trim() + " ', docs = '" + this.docscombobox.Text.Trim() + "' , where username = '" + this.usernamelable.Text.Trim() + "' ;";
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(Query, conwaqDatabase);
MySqlDataReader myreader;

try {
    conwaqDatabase.Open();
    myreader = cmdwaqDatabase.ExecuteReader();
    while (myreader.Read()) { }

    MessageBox.Show("Credential informations are updated");

    conwaqDatabase.Close();
}

catch {

}

1 个答案:

答案 0 :(得分:0)

你可以使用这样的东西。在sql命令中添加占位符,然后在运行ExecuteReader之后添加参数值。

string constring = string.Format("datasource='{0}';port='{1}';database='{2}';username=claimsprologin;password=gfx)C#G$aD3bL`@;Connect Timeout=180;Command Timeout=180", serveriplable.Text, portno.Text, databasenamelable.Text);
string Query = "update claimloans set loannumber= @loannumbertextbox, pool = @loanpooltextbox, disblid = @disbidtextbox, category = @categorytxtbox, subcacategory = @subcategorytxtbox, invoice = @invoicenumbertextbox, invoicedate = @invoicedatetextbox, docs = @docscombobox, where username = @usernamelable;";
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(Query, conwaqDatabase);

cmdwaqDatabase .Parameters.AddWithValue("@loannumbertextbox", this.loannumbertextbox.Text.Trim());