在C#
我想运行SQL查询并将结果解析为QueryString
以传递到网页。在我的测试,我想这样做,但我得到从查询结果中创建查询字符串
关键的错误已经存在
什么是不正确或什么是做到这一点的正确方法是什么?
private void PrepQuery()
{
Dictionary<string, string> dictFormValues = new Dictionary<string, string>();
string connectionString = null;
SqlConnection cnn;
SqlCommand cmd;
StringBuilder sql = new StringBuilder();
SqlDataReader reader;
connectionString = "Data Source=server;Initial Catalog=database;User ID=;Password=";
sql.Append("select employeename, employeeaddress, employeezip, employeecity, employeestate, employeephone ");
sql.Append("from abcd ");
sql.Append("where validated is not null ");
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql.ToString(), cnn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
dictFormValues.Add("employeename", reader.GetValue(0).ToString());
dictFormValues.Add("employeeaddress", reader.GetValue(1).ToString());
dictFormValues.Add("employeezip", reader.GetValue(2).ToString());
dictFormValues.Add("employeecity", reader.GetValue(3).ToString());
dictFormValues.Add("employeestate", reader.GetValue(4).ToString());
dictFormValues.Add("employeephone", reader.GetValue(5).ToString());
name = reader.GetValue(0).ToString();
}
reader.Close();
cmd.Dispose();
cnn.Close();
}
bool success = false;
success = FormatForWebAPI();
if (success = true; { GenerateEmail();
if (sucess = false;) { ShowErrorOnScreen(); }
}
private void FormatForWebAPI();
{
string strEndpointURL = string.Format("http://requestb.in/pm9rstuv/");
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
foreach (var d in dictFormValues) { strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&"; }
strPostData += "hs_context=";
System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strEndpointURL);
r.Method = "POST";
r.Accept = "application/json";
r.ContentType = "application/x-www-form-urlencoded";
r.ContentLength = strPostData.Length;
r.KeepAlive = false;
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(r.GetRequestStream()))
{
try { sw.Write(strPostData); }
catch { return false; }
}
return true;
}
看起来你的数据中有重复。 Dictionarys不允许重复键。为什么你要使用字典而不是可能是元组列表的任何特定原因(请参阅:http://www.dotnetperls.com/tuple)? – sr28
@FunFlyWhiteGuy你错过了一个'catch'块 – MethodMan
你循环的结果,所以如果有n行你尝试添加n个关键字的名字不是'employeename'。请参阅[如何在C#中为URL创建查询字符串?](http://stackoverflow.com/questions/829080/how-to-build-a-query-string-for-a-url-in-c) –