【问题标题】:how can i loop through all of the columns of the OracleDataReader我如何遍历 OracleDataReader 的所有列
【发布时间】:2011-02-28 23:42:37
【问题描述】:

我有以下代码,我想遍历此查询结果中的所有字段并填充名为字段的字典。

如果有数据阅读器,这可能吗?

            OracleCommand command = connection.CreateCommand();
            string sql = "Select * from MYTABLE where ID = " + id;
            command.CommandText = sql;

            Dictionary<string, string> fields = new Dictionary<string, string>();
            OracleDataReader reader = command.ExecuteReader();

【问题讨论】:

    标签: c# sql datareader


    【解决方案1】:

    你应该可以做这样的事情:

    Dictionary<string, string> fields = new Dictionary<string, string>();
    OracleDataReader reader = command.ExecuteReader();
    
    if( reader.HasRows )
    {
        for( int index = 0; index < reader.FieldCount; index ++ )
        {
            fields[ reader.GetName( index ) ] = reader.GetString( index );
        }    
    }
    

    【讨论】:

    • 如果你的数据不是字符串,你应该用这个交换for循环的内部:fields[reader.GetName(index)] = reader.GetValue(index).ToString() ;
    【解决方案2】:

    GetSchemaTable 将返回有关列的大量信息,包括它们的名称以及大小、类型等。

    我假设您希望字典的键是列名,值是行值。如果是这样,这应该工作:

    var dict = reader.GetSchemaTable().Rows.OfType<DataRow>().Select(
        r => r["ColumnName"].ToString()
    ).ToDictionary(
        cn => cn,
        cn => reader[cn].ToString()
    );
    

    您也可以使用GetValues() 来获取列数,并为每列调用GetName(int)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 2020-04-14
      • 2018-07-23
      相关资源
      最近更新 更多