2013-05-17 21 views
0

我试图用我的web应用程序中的1个按钮更新2个不同的表格。我目前正在使用asp.net开发我的web应用程序。我想知道是否有可能从2个不同的表中更新2个不同的列。用asp.net中的1个按钮更新2个不同的表格

这里是我的后端代码

protected void btnAssign_Click(object sender, EventArgs e) 
    { 
     //SqlConnection connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI"); 

     //connAdd.Open(); 
     //string mySQL; 
     //mySQL = "Update LoginRegisterPoliceOfficer Set caseid ='" + lblCID.Text + "' where fullname ='" + DDLpolice.SelectedItem.Text + "'"; 
     //SqlCommand cmdAdd = new SqlCommand(mySQL, connAdd); 
     //cmdAdd.ExecuteNonQuery(); 

     //connAdd.Close(); 



     SqlConnection connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI"); 

     connAdd.Open(); 
     string mySQLL; 
     mySQLL = "Update Report Set handle = 'handled' where caseid='"+lblCID.Text+"'"; 
     SqlCommand cmdAdd = new SqlCommand(mySQLL, connAdd); 
     cmdAdd.ExecuteNonQuery(); 

     connAdd.Close(); 


    } 

我只能够更新1,但失败,第二次更新。因此,我注释掉了我的一个sql代码。

回答

1

如果您对两个表使用相同的数据库,则无需关闭并打开连接。使用相同的连接,并逐个执行2个语句。需要

protected void btnAssign_Click(object sender, EventArgs e) 
{ 
    using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI")) 
    { 
     connAdd.Open(); 
     var sql = "Update LoginRegisterPoliceOfficer Set caseid ='" + lblCID.Text + "' where fullname ='" + DDLpolice.SelectedItem.Text + "'"; 
     using(var cmdAdd = new SqlCommand(sql, connAdd)) 
     { 
      cmdAdd.ExecuteNonQuery(); 
     } 

     sql = "Update Report Set handle = 'handled' where caseid='"+lblCID.Text+"'"; 
     using (var cmdAdd = new SqlCommand(mySQLL, connAdd)) 
     { 
       cmdAdd.ExecuteNonQuery(); 
     } 

     connAdd.Close(); 
    } 
} 

using statement所以.NET运行时回收内存当对象被销毁,可能会丢失,没有他们,你的代码引入了内存泄漏这会影响你的网站的性能(除其他事项外)。

var statement是一种简洁的声明变量的方式。我喜欢在=符号的右侧显示变量类型时使用它,否则代码看起来冗余且冗长。

最后,这段代码很容易出现sql injection attack。用张贴值构造sql可能非常危险。如果值lblCID.Text是'(drop table LoginRegisterPoliceOfficer)',该怎么办?一个更安全的方式来执行查询是通过使用存储过程或sql parameters

+0

谢谢你的工作。 :) –

0

是的,你可以。您应该能够在单个ASP.NET函数中执行任意数量的更新,前提是您不会遇到超时或意外关闭要打开的某些内容。

让SqlConnection对象保持打开状态,并创建两个sqlCommand实例。或者将你的两个UPDATE作为单个字符串发送,在它们之间带有换行符和分号。或者将逻辑移到服务器端,并有一个知道要更新它们的存储过程。 (你可以做一个可更新的视图?)

相关问题