在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) –