【问题标题】:Show results of SQL query using DataTable in a console application? [duplicate]在控制台应用程序中使用 DataTable 显示 SQL 查询的结果? [复制]
【发布时间】:2020-08-11 17:40:30
【问题描述】:

我正在尝试从控制台应用程序对 SQL Server 运行 SQL 查询,但我无法在控制台上操作或显示此数据。

我试过这个:

static void Main(string[] args)
{
    string conexao = @"Integrated Security=SSPI;Persist Security Info=False;" +
         "Initial Catalog=Linhas;Data Source=HP\SQLEXPRESS";
    SqlConnection cn = new SqlConnection(conexao);
    SqlDataAdapter Da_fun = new SqlDataAdapter(
       @"select top 1 Name as '[NAME_USER]',Adress as '[ADRESS_USER]' " +
              "from TB_User order by ID_User asc", cn);
    DataTable Tb_fun = new DataTable();
    Da_fun.Fill(Tb_fun);
    Console.WriteLine(Tb_fun);

    Console.ReadKey();
}

打印类似“System.Data.DataTable”的内容,而不是格式精美的多列布局。

【问题讨论】:

  • 这能回答你的问题吗? Print Contents Of A DataTable
  • 如果它是一个控制台应用程序,它不是 ASP.NET Core,是吗?请不要在您的问题中添加不相关的标签。如果您不确定其中的区别,请阅读.NET Core vs ASP.NET Core
  • 显示的代码确实“从控制台应用程序运行 SQL Server 的 SQL 查询”,所以这不是问题(除非有错误,应该报告)因此应该 not 是标题。然后 1) 没有与操作相关的代码 2) 真正的问题似乎是 DataTable.ToString 不能方便地返回格式化表(它仍然会打印一些东西,这应该是一个线索).. 努力隔离具体问题并在提出问题时提供相关意见。

标签: c# sql-server .net-core console-application


【解决方案1】:

数据表是行和列的集合因此,您需要遍历行,然后需要打印每个单元格值。见下例:

static DataTable GetTable()
    {
        DataTable table = new DataTable(); // New data table.
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));
        table.Rows.Add(15, "Abilify", "Jacob", DateTime.Now);
        table.Rows.Add(40, "Accupril", "Emma", DateTime.Now);
        table.Rows.Add(40, "Accutane", "Michael", DateTime.Now);
        table.Rows.Add(20, "Aciphex", "Ethan", DateTime.Now);
        table.Rows.Add(45, "Actos", "Emily", DateTime.Now);
        return table; // Return reference.
    }
    private static void Main(string[] args)
    {
        DataTable table = GetTable();
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine("--- Row ---");
            foreach (var item in row.ItemArray)
            {
                Console.Write("Item: "); // Print label.
                Console.WriteLine(item);
            }
        }
        Console.Read(); // Pause.

    }

//Output
--- Row ---
Item: 15
Item: Abilify
Item: Jacob
Item: 4/28/2020 7:18:18 AM
--- Row ---
Item: 40
Item: Accupril
Item: Emma
Item: 4/28/2020 7:18:18 AM
--- Row ---
Item: 40
Item: Accutane
Item: Michael
Item: 4/28/2020 7:18:18 AM
--- Row ---
Item: 20
Item: Aciphex
Item: Ethan
Item: 4/28/2020 7:18:18 AM
--- Row ---
Item: 45
Item: Actos
Item: Emily
Item: 4/28/2020 7:18:18 AM

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多