从 oracle 数据库打印整个 table 的 C# 程序

C# program to Print whole table from oracle database

hr有很多table。 我想编写一个程序来允许用户输入 table 名称,我必须将 table 中的所有数据打印到控制台。

问题是所有 table 的结构都不同。我的意思是在不同的 table 中有不同的属性。如何打印来自特定 table 的所有数据?

我写了下面的代码。如何打印所有 table 数据?

using System;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;

namespace Ass1Que1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
               string constr = "DATA SOURCE=localhost:1521/orclpdb;PERSIST SECURITY INFO=True;USER ID=HR;password=hr";
                string table = "";
                OracleConnection con = new OracleConnection(constr);
                con.Open();
                Console.WriteLine("Connected to Oracle Database {0}", con.ServerVersion);
                // con.Dispose();
                Console.Write("Enter the table name: ");
                table = Console.ReadLine();
                OracleCommand cmd = con.CreateCommand();
                cmd.CommandText = "SELECT * FROM " + table;
                OracleDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("" + reader.GetString(0));
                }
                Console.WriteLine("Press RETURN to exit.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : {0}", ex);
                Console.ReadKey();
            }
        }
    }
}

代码对我来说工作正常,但我只想打印所有数据意味着我想打印 Select * 的输出。它应该适用于所有 tables.

这是一个基于我的评论的简单示例。请注意,它未经过测试,但该理论基于类似 SqlDataReader。下面的代码片段将打印列名和值(理论上至少):

OracleDataReader reader = cmd.ExecuteReader();
var cols = reader.FieldCount;

while (reader.Read())
{
    for (int i = 0; i < cols; i++)
    {
        Console.WriteLine("{0}: {1}", reader.GetName(i), reader.GetValue(i));
    }
}

您也许也可以做到 Console.WriteLine("{0}: {1}", reader.GetName(i), reader[i]); - 您可以使用 SqlDataReader 做到这一点,但我不能 100% 确定 OracleDataReader.