我用这段代码创建了一个备份表单:
private void btnBackUp_Click(object sender, EventArgs e) //Backup will work only when we place |DataDirectory| in our appconfig file
{
try
{
progressBar1.Visible = true;
progressBar1.Value = 15;
bool bBackUpStatus = true;
Cursor.Current = Cursors.WaitCursor;
if (Directory.Exists(@"D:Backup_MAConvent"))
{
if (File.Exists(@"D:Backup_MAConventMAConvent_Backup.bak"))
{
if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
File.Delete(@"D:Backup_MAConventMAConvent_Backup.bak");
}
else
bBackUpStatus = false;
}
}
else
Directory.CreateDirectory(@"D:Backup_MAConvent");
if (bBackUpStatus)
{
con.Open();
progressBar1.Value = 25;
string path1 = System.IO.Path.GetFullPath(@"SchoolDatabase.mdf");
SqlCommand cmd2 = new SqlCommand("backup database [" + path1 + @"] to disk ='D:Backup_MAConventMAConvent_Backup.bak' with init,stats=10", con);
cmd2.ExecuteNonQuery();
progressBar1.Value = 35;
con.Close();
timer1.Start();
MessageBox.Show("Backup of the Database saved Successfully", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
timer1.Stop();
progressBar1.Value = 10;
progressBar1.Visible = false;
}
}
catch
{
MessageBox.Show(@"Backup Error, Please close the software & restart and then try again to backup", "Backup", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
此代码不适用于数据库的连接字符串bin
。因此,我将 app.config
中的连接字符串更改为 |DataDirectory|
<connectionStrings>
<add name="SchoolManagement.Properties.Settings.SchoolDatabaseConnectionString"
connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|SchoolDatabase.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
之后,当我向数据库插入新值时,这些值是临时显示在具有搜索查询的搜索表单中。但是停止调试后,数据不在数据库中。
然后我Copy To output directory
更改为copy if newer
. 因此,现在数据每次都显示在表单的搜索网格视图中,但它不会显示在服务器资源管理器的数据库中(显示表数据)。
我知道此问题是由于|Data directory|
数据库和\bin数据库而发生的。请建议该怎么做?如果我将连接字符串更改为 \bin 数据库,一切正常,但备份代码不起作用。如果有人知道解决这个问题的方法,请提供帮助。谢谢
整个用户实例和 AttachDbFileName= 方法充其量是有缺陷的!在 Visual Studio 中运行应用时,它将围绕.mdf
文件进行复制(从App_Data
目录复制到输出目录 - 通常.bindebug
- 应用运行的位置),并且很可能,你的INSERT
工作正常 - 但你最终只是看错了.mdf文件!
如果您想坚持使用这种方法,请尝试在myConnection.Close()
调用上放置断点 - 然后使用 SQL Server Mgmt Studio Express 检查.mdf
文件 - 我几乎可以肯定您的数据就在那里。
在我看来,真正的解决方案是
-
安装 SQL Server Express(无论如何,您已经这样做了)
-
安装 SQL Server Management Studio Express
-
在 SSMS Express 中创建数据库,为其指定一个逻辑名称(例如
SchoolDatabase
) -
使用其逻辑数据库名称(在服务器上创建它时给出)连接到它 - 并且不要弄乱物理数据库文件和用户实例。在这种情况下,连接字符串将如下所示:
Data Source=.\SQLEXPRESS;Database=SchoolDatabase;Integrated Security=True
其他一切都和以前一模一样...
另请参阅Aaron Bertrand的优秀博客文章Bad habits to kick: Using AttachDbFileName以获取更多背景信息。