首页 > 解决方案 > Visual Studio Server Explorer 显示表数据为空

问题描述

我正在开发一个带有基于服务的数据库的 Winforms c# 程序。我创建了一个名为的表,该表Books为空且当前没有记录。

使用一些代码,我将插入表值。出于某种原因,当单击“显示表数据”时,尽管我添加了一条记录,但它仍然显示为空白。

DataGridView我通过使用它的数据源是表来检查记录是否存在(但隐藏)Books。我可以看到记录已创建,但由于某种原因未显示在服务器资源管理器的“显示表数据”视图中。

这是我在表中插入新记录的代码:

string query = "INSERT INTO Books (ISBN, Title, Authors, Publishers, Genre, Page_Count, Quantity) VALUES (@isbn, @title, @authors, @publishers, @genre, @page_count, @quantity)";
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\LMSDB.mdf;Integrated Security=True";

// Establish connection with database
using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Avoid SQL injection using parameters. Replace them with their real values
    SqlCommand command = new SqlCommand(query, connection);
    command.Parameters.AddWithValue("@isbn", isbn);
    command.Parameters.AddWithValue("@title", title);
    command.Parameters.AddWithValue("@authors", authors);
    command.Parameters.AddWithValue("@publishers", publishers);
    command.Parameters.AddWithValue("@genre", genre);
    command.Parameters.AddWithValue("@page_count", pageCount);
    command.Parameters.AddWithValue("@quantity", quantity);

    try
    {
        connection.Open();
        if (command.ExecuteNonQuery() == 1)
        {
            // 1 Row affected. Success
            Console.WriteLine("Book added to database successfully");
            ClearControlValues();
            
        }
        
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error occured:\n" + ex.Message);
    }
    finally
    {
        connection.Close();
    }
}

显示表数据选项 表格数据显示为空白

如您所见,“显示表数据”视图显示为空白,尽管我知道有一条记录,我可以在DataGridView

关于为什么记录没有出现,我有什么遗漏吗?

编辑:感谢史蒂夫指出服务器资源管理器和我的代码有不同的连接字符串。改变了这些,我现在有了预期的结果。

标签: c#sqlsql-servervisual-studiowinforms

解决方案


我用你的代码做了一个测试,可以成功插入数据。

正如史蒂夫所说,问题在于您的连接字符串。您可以通过以下步骤找到您的连接字符串:

1.右键单击连接名称并选择属性。

2.Properties 窗口中有一个名为Connection String 的项目。如下: 在此处输入图像描述

张勇


推荐阅读