【问题标题】:Displaying values from a SQL database in C# console application在 C# 控制台应用程序中显示 SQL 数据库中的值
【发布时间】: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 go select * 被认为是不好的做法,架构可能会更改(添加列,移动列,...)而不是指定列,如果您想在应用程序中显示数据的来源,则将其编码。跨度>
  • 您有任何异常吗? using 语句隐藏了一些我更喜欢使用 try/catch 并显示异常的异常。

标签: c# sql


【解决方案1】:

该代码实际上会引发异常。您在连接字符串中用方括号将名称括起来,这会导致连接失败。将其更改为:

using (SqlConnection connection = new SqlConnection("Server=SQ_SIXTEEN;Database=PocketCentral;Trusted_Connection=true"))

请注意,当 Trusted_Connection 为 true(Windows 身份验证)时,您不使用 UserID 和 Password。

编辑:附加说明。

您通常会知道您的数据内容(您的列名和类型)。从 SQL 的角度来看,建议您列出所有列。即:不要简单地使用“select *”,而是使用“select firstName, lastName, ... from ...”之类的东西。

根据读者,您使用 reader[index] 而不是 reader.GetValue[i] 并将类型转换为应有的类型:

(int)reader[0]
(DateTime)reader["OrderDate"]

整数索引更快,但取决于列位置,使用列名的字符串索引更具可读性。

EDIT2:不要跳过查看 LINQ。恕我直言,这更容易。

【讨论】:

  • 这是问题所在,我删除了方括号,控制台显示了所有内容。尽管使用方括号,控制台并没有抛出异常,它只是保持空白。我也将研究 LINQ。谢谢
猜你喜欢
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多