从查询结果创建查询字符串

时间:2016-01-13 16:38:01

标签: c# asp.net query-string

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;
}

1 个答案:

答案 0 :(得分:0)

基本上词典不允许重复键。来自MSDN - Dictionary

  

词典中的每个键都必须是唯一的   字典的平等比较。

在您的情况下,您正在添加&#39; employeename&#39;,&#39; employeeaddress&#39;等作为你词典的关键。因此,从它的外观来看,如果你希望有超过1名员工(或一行数据),那么你将得到这个错误,因为每个1它将尝试再次添加相同的密钥(employeename等)

根据我的评论,请尝试使用Tuples,例如List<tuple<string, string>>。存在各种其他存储数据的方法,其中包含重复项,例如DataTable或xml文档中的重复项。一旦你真的得到它,这真的取决于你打算用它做什么。

或者创建自己的类型&#39;员工&#39;包含您要存储的所有信息的属性(名称,地址,邮政编码等),然后创建一个列表,如List<employee>