【发布时间】:2018-07-19 17:22:45
【问题描述】:
我正在尝试连接到 C# 中的数据库并显示某些数据点。数据库有许多列和表,我只想使用 Writeline() 在控制台中显示它们。以下是我到目前为止所拥有的。代码运行没有错误,但也不显示任何内容。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Sql;
namespace SQLIntro
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection("Server=[SQ_SIXTEEN];Database=[PocketCentral];User ID=[un];Password=[pw];Trusted_Connection=true"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM tbl_Terminal", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
Console.WriteLine();
}
}
}
}
}
}
}
一件事是列信息的去向... SQL 命令?还是在while循环中?
【问题讨论】:
-
SELECT * FROM tbl_Terminal是否返回任何记录? -
where the column info would goselect * 被认为是不好的做法,架构可能会更改(添加列,移动列,...)而不是指定列,如果您想在应用程序中显示数据的来源,则将其编码。跨度> -
您有任何异常吗? using 语句隐藏了一些我更喜欢使用 try/catch 并显示异常的异常。