【发布时间】: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 解决,他指出服务器资源管理器和我的代码有不同的连接字符串。改变了这些,我现在有了预期的结果。
【问题讨论】:
-
因为您在代码中使用 DataDirectory 指向您的数据库,而 Server Explorer 使用另一个连接字符串指向不同的数据库。见stackoverflow.com/questions/17147249/…
标签: c# sql sql-server visual-studio winforms