我需要建议。我有asp.net web服务和winforms客户端应用程序。 客户端调用此Web方法并获取数据集。使用数据集更新数据源
1. [WebMethod]
2. public DataSet GetSecureDataSet(string id)
3. {
4.
5.
6. SqlConnection conn = null;
7. SqlDataAdapter da = null;
8. DataSet ds;
9. try
10. {
11.
12. string sql = "SELECT * FROM Tab1";
13.
14. string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString;
15.
16. conn = new SqlConnection(connStr);
17. conn.Open();
18.
19. da = new SqlDataAdapter(sql, conn);
20.
21. ds = new DataSet();
22. da.Fill(ds, "Tab1");
23.
24. return ds;
25. }
26. catch (Exception ex)
27. {
28. throw ex;
29. }
30. finally
31. {
32. if (conn != null)
33. conn.Close();
34. if (da != null)
35. da.Dispose();
36. }
37. }
在他完成工作后,他将此更新方法称为Web方法。他可以在数据集的表中添加,删除和编辑行。在客户端
[WebMethod]
public bool SecureUpdateDataSet(DataSet ds)
{
SqlConnection conn = null;
SqlDataAdapter da = null;
SqlCommand cmd = null;
try
{
DataTable delRows = ds.Tables[0].GetChanges(DataRowState.Deleted);
DataTable addRows = ds.Tables[0].GetChanges(DataRowState.Added);
DataTable editRows = ds.Tables[0].GetChanges(DataRowState.Modified);
string sql = "UPDATE * FROM Tab1";
string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString;
conn = new SqlConnection(connStr);
conn.Open();
cmd = new SqlCommand(sql, conn);
da = new SqlDataAdapter(sql, conn);
if (addRows != null)
{
da.Update(addRows);
}
if (delRows != null)
{
da.Update(delRows);
}
if (editRows != null)
{
da.Update(editRows);
}
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn != null)
conn.Close();
if (da != null)
da.Dispose();
}
}
代码
1. //on client side is dataset bind to datagridview
2. Dataset ds = proxy.GetSecureDataSet("");
3. ds.AcceptChanges();
4.
5. //edit dataset
6.
7.
8. //get changes
9. DataSet editDataset = ds.GetChanges();
10.
11. //call update webmethod
12. proxy.SecureUpdateDataSet(editDataSet)
但与此错误完成:
System.Web.Services.Protocols.SoapException:服务器无法处理请求。 ---> System.InvalidOperationException:在使用修改的行传递DataRow集合时,Update需要有效的UpdateCommand。 在WebService.Service.SecureUpdateDataSet(数据集DS)在d:\ Diploma.Work \ WebService的\ Service1.asmx.cs:线489
问题是与SQL Commad,客户端可以添加,删除和插入行,如何可以编写一个corect SQL命令....有什么建议吗?谢谢
使用到位的 “使用” 语句的try-catch-finally块的SqlConnection的。方便,并使代码块看起来更短。 :-) – 2010-03-28 05:16:55