2013-11-24 36 views
1
using System.Data.SqlClient; 
using System.Data.Sql; 

public partial class _Default : System.Web.UI.Page 
{ 


SqlConnection con = new SqlConnection(@"Data Source=GAGAN-PC\SQLEXPRESS;Initial Catalog=update_test;Integrated Security=True"); 
    SqlCommand cmd; 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
    protected void delete_button_Click(object sender, EventArgs e) 
    { 
     con.Open(); 
     cmd = new SqlCommand("delete from update_delete where id like'"+TextBox1.Text+"'",con); 
     cmd.ExecuteNonQuery(); 
     Response.Write("Control reached."); 
     con.Close(); 
     Response.Write("Data successfully deleted."); 
    } 
    protected void update_button_Click(object sender, EventArgs e) 
    { 
     con.Open(); 
     cmd = new SqlCommand("update update_delete set password ='"+TextBox3.Text+"' where id like'"+TextBox2+"'", con); 
     cmd.ExecuteNonQuery(); 
     Response.Write("Control reached."); 
     con.Close(); 
     Response.Write("Data successfully Updated."); 
    } 
} 

我想實現更新查詢,但有一點問題。我已經使用SQL Server作爲數據庫,並且update_delete是一個表格,其中有3列id,sname,password,我試圖根據id更新密碼。更新查詢不起作用在ASP.NET web應用程序

問題是當我點擊更新按鈕控件時達到cmd.ExecuteNonQuery();沒有顯示錯誤。但更新沒有發生。我該怎麼辦。請請請幫助我。提前致謝。 :) :)

+1

這麼多'IDisposable'對象。所以很少有'Dispose'調用:( –

+1

所以很多查詢,很少的參數 - 非常多的SQL注入**危險! –

+0

錯誤的,marc_s。你可以使用LIKE OPERATOR和INT等數字數據類型。不清楚爲什麼有人但它確實按預期運行 – laylarenee

回答

1

我想你會得到一個例外。我會建議趕上你的異常並告訴我們信息...你可以使用調試器或try-catch子句捕捉異常。

如果您沒有收到異常並顯示「控制已達到」消息,則必須使用已形成的SQL字符串直接在SQL Server中使用它,並查看SQL語句中是否有錯誤。我想你會以某種方式形成無效的SQL語句(例如使用不存在的ID)。

希望我幫了忙!

2

我只是猜測在這裏 - 如果Id是一個數字數據類型,那麼你不能使用LIKE它。

另請參見:請使用using()...塊以確保正確處理和使用參數化查詢以避免SQL注入攻擊。

撰寫您UPDATE命令是這樣的:

protected void update_button_Click(object sender, EventArgs e) 
{ 
    // get the values to use 
    string idValue = Convert.ToInt32(TextBox3.Text.Trim()); 
    string password = TextBox2.Text.Trim(); 

    // define the query text with *parameters* ! 
    string updateQuery = "update update_delete set password = @password where id = @ID"; 

    // put things like SqlConnection and SqlCommand into "using()...." blocks 
    using (SqlCommand updCmd = new SqlCommand(updateQuery, con)) 
    { 
     // define parameters and their values 
     updCmd.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = password; 
     updCmd.Parameters.Add("@ID", SqlDbType.Int).Value = idValue; 

     con.Open(); 
     cmd.ExecuteNonQuery(); 
     con.Close(); 

     Response.Write("Data successfully Updated."); 
    } 
} 
+1

另一個重要的注意事項是密碼不應該以純文本形式存儲 – laylarenee

+0

'//定義參數和它們的值'是否有指定類型的意義?我知道一些參數必須(例如TVPs),否則'AddWithValue'對我來說一直很好,它的代碼少得多。 –

+0

@ ta.speot.is:這只是個人偏好 - 我p請參閱**告訴** ADO.NET我的類型是什麼,而不是讓它猜出我提供的值。如果你傳入NULL值,應該猜到什麼? –