【发布时间】:2015-10-23 05:43:47
【问题描述】:
我正在使用此方法返回 XML 作为结果。执行存储过程后,我需要返回一个 json 对象。我应该在哪里编辑以下代码以返回 JSON 对象?
public XmlElement GetGraphData(int eventTypeID, int patientID)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("sp_GetGraphData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@EventID", eventTypeID);
cmd.Parameters.AddWithValue("@PatientID", patientID);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
XmlDataDocument xmldata = new XmlDataDocument(ds);
XmlElement xmlElement = xmldata.DocumentElement;
}
【问题讨论】:
-
您想将数据集转换为 json 对象。对吗?
-
旁注:您应该不为您的存储过程使用
sp_前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实会在未来某个时候冒着名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免sp_并使用其他东西作为前缀 - 或者根本不使用前缀! -
另外 - 你正在执行查询两次 - 一次在
ExecuteNonQuery,第二次在da.Fill(ds)- 不要那样做!你想做什么?从数据库加载数据?不要为此使用ExecuteNonQuery!此调用仅适用于不返回任何数据的 SQL 语句! (如INSERT、DELETE) -
是的,Amey Deshpande .. 你是对的
-
你可以使用
Newtonsofts Json.Net
标签: c# sql-server json xml stored-procedures