-1

对此进行了谷歌搜索,我似乎找不到任何引用如何将 sql 选择查询加载到键值对列表中的地方。

 {
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())
  {

    }
 }

}

执行查询后如何将值和描述加载到键值对列表中。键值对

4

1 回答 1

4

您没有提到您使用什么技术来执行查询,所以我假设您使用的是一种不会自动映射到类的基本技术。

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

  1. 遍历您收到的每一行
  2. KeyValuePair使用适合列的类型创建一个新对象(通常是string, stringint, string
  3. 将 的值设置为KeyValuePair您从阅读器读取的每一列的值。
  4. 如果您想对后者做其他事情,请尝试在迭代期间KeyValuePair将其添加到 aList<KeyValuePair>

编辑好的,所以根据您的编辑,我猜您是新手。您提到您正在使用 DB2。您没有明确说明您使用哪个库从 DB2 中读取数据,因此我假设它是 IBM 提供的库。我将根据 IBM 的DB2DataReader 类文档提供信息。

以下应该有效(前提是我没有输入错误)。我在此过程中包含了一些评论以提供帮助:

// 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 
于 2012-11-09T16:16:54.823 回答