我正在尝试从控制台应用程序运行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();
}
需要帮助。有任何建议/想法吗?
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