我如何循环遍历 OracleDataReader 的所有列

发布于 2024-09-05 02:22:13 字数 425 浏览 3 评论 0原文

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

给定一个数据读取器,这可能吗?

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

I have the following code and i want to loop through all the fields in the result of this query and populate the dictionary called field.

Given a datareader is this possible?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

念﹏祤嫣 2024-09-12 02:22:41

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

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

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

您还可以使用 GetValues() 获取列数,并调用 GetName(int) 对于每个。

GetSchemaTable will return a lot of information about the columns, including their name but also size, type, etc.

I presume you want the key of the dictionary to be the column name, and the value to be the row value. If so, this should work:

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

You could also use GetValues() to get the number of columns, and call GetName(int) for each.

飘然心甜 2024-09-12 02:22:32

你应该能够做这样的事情:

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

You should be able to do something like this:

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 );
    }    
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文