C# WinForm插入数据后Visual Studio Server Explorer表数据显示为空
问题现象
我正在开发C# WinForm程序,使用基于服务的数据库,已创建空表Books。通过代码向表中插入记录后,点击Visual Studio Server Explorer的Show Table Data选项,视图显示空白,但将Books表作为数据源绑定到DataGridView时,可正常看到已插入的记录。
插入新记录的代码如下:
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"; // 建立数据库连接 using (SqlConnection connection = new SqlConnection(connectionString)) { // 使用参数避免SQL注入,替换为实际值 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行受影响,插入成功 Console.WriteLine("图书已成功添加到数据库"); ClearControlValues(); } } catch (Exception ex) { MessageBox.Show("发生错误:\n" + ex.Message); } finally { connection.Close(); } }
附带两张截图:第一张为Show Table Data选项入口,第二张为空白的表数据视图。
问:是什么原因导致已插入的记录无法在Server Explorer的表数据视图中显示?
问题原因&解决方法
这个问题的核心是Server Explorer连接的数据库文件和代码运行时操作的不是同一个文件:
- 代码中的连接字符串用了
|DataDirectory|占位符,WinForm项目默认编译运行时,|DataDirectory|指向的是编译输出目录(比如bin/Debug或者bin/Release)下的数据库文件,代码插入操作是写到这个目录下的LMSDB.mdf里的。 - 而Server Explorer默认连接的是项目根目录下的原始
LMSDB.mdf文件,自然看不到写入到输出目录数据库里的记录。
你可以直接复制代码中使用的连接字符串,替换掉Server Explorer里对应数据库连接的连接字符串,就能看到插入的记录了。
编辑补充:问题已解决,修改Server Explorer的连接字符串和代码保持一致后即可正常查看数据。
内容的提问来源于stack exchange,提问作者Luke C
相关产品推荐
相关产品推荐

