【问题标题】:Visual Studio Server Explorer show table data is blankVisual Studio Server Explorer 显示表数据为空
【发布时间】:2021-10-18 21:33:57
【问题描述】:

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

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

我通过使用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 上可以看到一条记录

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

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

【问题讨论】:

标签: c# sql sql-server visual-studio winforms


【解决方案1】:

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

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

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

2.Properties 窗口中有一个名为Connection String 的项目。 如下:

张勇

【讨论】:

    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多