将数据从sql select加载到keyvaluepair<>

时间:2012-11-09 16:11:41

标签: c# sql key-value

用Google搜索,我似乎无法找到任何引用如何将sql select查询加载到keyvaluepair列表的地方。

 {
Keyvaluepair<int, name> D =new keyvaluepair <Int, name>

Using (db2connection conn =new db2connection())
 {
   Db2command cms =new db2command();

String select=    ( @"Select distinct Value, Descrip
      From cool", conn)
   Using(db2reader read =new db2reader())
  {

    }
 }

}

如何在执行查询后将值和Descrip加载到keyvaluepair列表中。 Keyvaluepair

1 个答案:

答案 0 :(得分:4)

您还没有提到您用于执行查询的技术,因此我假设您使用的是不会自动映射到类的基本技术。

这很容易做到。你要做的就是:

  1. 迭代您收到的每一行
  2. 使用适合列的类型创建新的KeyValuePair对象(通常为string, stringint, string
  3. KeyValuePair的值设置为您从阅读器中读取的每列的值。
  4. 如果您希望稍后使用KeyValuePair执行其他操作,请尝试在迭代期间将其添加到List<KeyValuePair>
  5. 编辑好的,所以根据你的编辑,我猜你是新手。你提到你正在使用DB2。您还没有明确表示您正在使用哪个库来读取DB2,因此我将假设它是IBM提供的库。我将根据IBM的DB2DataReader class文档提供信息。

    以下内容应该有效(前提是我没有打字)。我已经在评论中提供了帮助:

    // this variable will have the data read from the server after all is said and done
    List<KeyValuePair<int, string>>> data = new List<KeyValuePair<int, string>>();
    
    // create the connection (replace connection string as necessary)
    using (DB2Connection conn = new DB2Connection("database connection string"))
    {
        // specify the query, create and open the command object 
        string qry = "Select distinct Value, Descrip from cool";
        DB2Command cmd = new DB2Command(qry, conn);
        conn.Open();
    
        // calling ExecuteReader() sends the query to the database and starts 
        // the process of reading the data
        using(DB2DataReader read = cmd.ExecuteReader())
        {
            // you have to call Read() for every row. It will return false if there 
            // are no more rows left
            while(read.Read())
            {
                // calling the various Get methods is how you get the data out of the reader
                // note that you pass in the index of the column for each call
                int intVal = read.GetInt32(0);
                string strVal = read.GetString(1);
    
                // now you're ready to create your KeyValuePair object
                KeyValuePair<int, string> tmp = new KeyVauePair<int, string>(intVal, strVal);
    
                // And add it to the list we defined at the start of this
                data.Add(tmp);
            }
        }
    }
    
    // and now we've got all of the data from your query wrapped up into a nice list
    // called 'data'. Do with it whatever you planned