【发布时间】:2012-06-25 16:27:34
【问题描述】:
这个 foreach 循环在测试时工作正常,只返回 5 行数据,但我很清楚它的编写有多糟糕,有没有更好的方法,可能使用 stringbuilder 更有效地重写它?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
SqlCommand comm = new SqlCommand("SELECT Title, StartDate FROM tblEvents JOIN eo_UserEventWatch ON eo_UserEventWatch.EventID=tblEvents.ID WHERE eo_UserEventWatch.UserID = @GUID ;", conn);
comm.Parameters.AddWithValue("GUID", userID);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
string result ="{ \"event\" :[";
foreach (DataRow dr in dt.Rows)
{
result += "{\"title\" : \"" + dr[0].ToString() + "\" , \"start\" : \"" + dr[1].ToString() +"\"} ,";
}
result = result.TrimEnd(',');
result += "] }";
return result;
【问题讨论】:
-
StringBuilder 更高效,但更冗长。
-
不要使用字符串操作构建
Json。使用 Json.Net、JavaScriptSerializer、DataContractJsonSerializer 等 json 解析器...否则,很容易得到无效的 json -
您应该使用 JSON 库来构建您的 JSON。
-
@TheGeekYouNeed 你测量了吗?该行被重写为 one 调用以连接。与最多四个追加调用相比,它不太可能特别慢
-
正如@JesseC.Slicer 所说,您确实需要处理连接、命令和数据适配器对象。要么将它们包装在 using 块中,要么关闭它们并将整个块包装在 try/catch/finally 中,然后在 finally 块中处理它们。
标签: c# asp.net sqlcommand