第一次尝试读取 SQL 服务器数据库,但 SqlDataAdapter.Fill(DataTable) 正在破坏它

Trying to read SQL Server Database for the first time but SqlDataAdapter.Fill(DataTable) is breaking it

这是我第一次使用数据库。

这是我的数据库,它只使用 Windows 身份验证。

我正在使用以下代码尝试连接到它并收集数据:

        string connectionString =   "user id=USERNAME;" +
                                    "server=SERVERNAME;" +
                                    "Trusted_Connection=yes;" +
                                    "database=claytonDatabase; " +
                                    "connection timeout=30";

        try
        {
            SqlConnection thisConnection = new SqlConnection(connectionString);
            thisConnection.Open();

            string Get_Data = "SELECT * FROM dbo.location";

            SqlCommand cmd = new SqlCommand(Get_Data);

            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("locationTable");

            sda.Fill(dt); // this line kills it

            foreach (DataRow dataRow in dt.Rows)
            {
                foreach (var item in dataRow.ItemArray)
                {
                    Console.WriteLine(item);
                }
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show("db error" + ex.ToString());
        }   

sda.Fill(dt); 行破坏了程序,如果我不使用 try 语句就会导致此错误:

An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

Additional information: 'The invocation of the constructor on type 'clayton.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'.

If there is a handler for this exception, the program may be safely continued.

如果我使用 try:

at line 0</StackTrace><ExceptionString>System.Windows.Markup.XamlParseException: 'The invocation of the constructor on type 'clayton.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'. ---&amp;gt; System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
   at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
   at clayton.MainWindow.ConnectToDatabase() in c:\Users\cclayto\Desktop\C#\clayton\clayton\MainWindow.xaml.cs:line 87
   at clayton.MainWindow..ctor() in c:\Users\cclayto\Desktop\C#\clayton\clayton\MainWindow.xaml.cs:line 34
   --- End of inner exception stack trace ---

我什至不确定如何测试问题是出在 Fill 命令上,还是我实际上根本没有成功连接到 SQL 数据库。任何建议都会非常有帮助!

您从未在您创建的 CMD 对象上设置连接字符串

cmd.Connection = thisConnection

错误消息虽然有点神秘,但确实告诉您错误是什么...

第 0System.Windows.Markup.XamlParseException 行: '对匹配指定绑定约束的 'clayton.MainWindow' 类型的构造函数的调用引发了异常。行号“3”和行位置“9”。 ---> System.InvalidOperationException: 填充: SelectCommand.Connection 属性 尚未初始化

Line 3, Position 9 不是 Fill 方法的位置,但是如果通过 XAML 文件中的某些绑定调用您的代码将失败,因为您的 SqlCommand 未与有效的 SqlConnection 关联,因此当您调用 Fill 时,无法找到数据库。

    string connectionString =   "user id=USERNAME;" +
                                "server=SERVERNAME;" +
                                "Trusted_Connection=yes;" +
                                "database=claytonDatabase; " +
                                "connection timeout=30";

    string Get_Data = "SELECT * FROM dbo.location";
    try
    {
        using(SqlConnection thisConnection = new SqlConnection(connectionString))
        using(SqlCommand cmd = new SqlCommand(Get_Data, thisConnection))
        using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            thisConnection.Open();
            DataTable dt = new DataTable("locationTable");
            sda.Fill(dt); 
            foreach (DataRow dataRow in dt.Rows)
            {
                 foreach (var item in dataRow.ItemArray)
                 {
                    Console.WriteLine(item);
                 }
            }
       }
   }
   catch(Exception ex)
   {
        MessageBox.Show("db error " + ex.Message);
   }   

不确定您在下面的评论中提到的错误。您可以尝试以这种方式更改循环以检查某些字段是否为 null

    foreach (DataRow dataRow in dt.Rows)
    {
         Console.WriteLine(dataRow.IsNull("Equipment Number") ? "NULL" : 
                           dataRow.Field<string>("Equipment Number"));
         Console.WriteLine(dataRow.IsNull("Equipment Description") ? "NULL" :
                           dataRow.Field<string>("Equipment Description"));
    }

附带说明一下,避免使用带空格的列名。他们给你带来的麻烦多于好处。