C# 在控制台应用程序中使用DataTable显示SQL查询的结果?
我试图从控制台应用程序运行SQL Server的SQL查询,但无法在控制台上操作或显示此数据 我试过这个:C# 在控制台应用程序中使用DataTable显示SQL查询的结果?,c#,sql-server,.net-core,console-application,C#,Sql Server,.net Core,Console Application,我试图从控制台应用程序运行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
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”的内容,而不是格式精美的多列布局 Datatable是行和列的集合,因此,您需要迭代行,然后需要打印每个单元格值。请参见以下示例:
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
这回答了你的问题吗?如果它是一个控制台应用程序,它不是ASP.NET核心,是吗?请不要在问题中添加不相关的标签。如果不确定差异,请阅读显示的代码“从控制台应用程序运行SQL Server的SQL查询”,因此这不是问题所在(除非有错误,应该报告),因此不应作为标题。然后1)没有与操作相关的代码,2)真正的问题似乎是DataTable.ToString不能方便地返回格式化的表(它仍然会打印一些东西,这应该是一个线索)。。在制定问题时,努力隔离具体问题并提供相关意见。