2010-06-08 135 views
8

我有下面的代碼,我想遍歷這個查詢結果中的所有字段並填充名爲字段的字典。我如何循環遍歷OracleDataReader的所有列

鑑於一個datareader是可能的嗎?

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

回答

16

你應該能夠做這樣的事情:

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

GetSchemaTable會返回大量的信息有關的欄目,包括姓名,而且大小,類型等

你想要的字典的關鍵是列名我相信,和值作爲行值。如果是的話,這應該工作:

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

你也可以使用GetValues()獲得的列數,並呼籲GetName(int)每個。