如何创建数据库备份,当数据库未存储在Microsoft SQL Server? [英] How to create database backup, when DB not stored in Microsoft SQL Server?
问题描述
我建立与SQL Server 2008 R2数据库中的C#应用程序,它存储在斌
我的项目文件夹中。我使用LINQ到SQL方法来创建数据库并将其附加到我的项目。
I am building a C# application with SQL Server 2008 R2 database which is stored in the bin
folder of my project. I use Linq to Sql method to create the database and attach it to my project.
这是我遇到的问题是,当我试图创建一个备份我的数据库。它抛出一个错误说
The problem that I'm having is that when I'm trying to create a backup of my database. It throws an error saying
数据库(数据库名称)不存在确保正确输入名称。 。BACKUP DATABASE异常终止
Database (database_name) does not exist make sure the name is entered correctly. BACKUP DATABASE is terminating abnormally.
下面是我写在我的按钮单击事件中的代码:
Here is the code that i write on my button click event:
try
{
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "SQL Server database backup files|*.bak";
sd.Title = "Create Database Backup";
if (sd.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string sqlStmt=string.Format("BACKUP DATABASE <database_name> TO DISK='{0}'",sd.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Backup Created Sucessfully");
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
我的连接字符串:
My Connection String:
string connStr = ConfigurationManager.ConnectionStrings["project_name.Properties.Settings.project_nameConnectionString"].ConnectionString;
,然后从我的app.config文件
and then from my app.config file
<add name="project_name.Properties.Settings.project_nameConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\database_name.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
因此,如果任何一个有我的问题的解决方案,这将是有益的。
so if any one have a solution to my problem that will be helpful.
推荐答案
很长一段时间头脑风暴之后,我终于succeded
所以,这里是解决方案:
After a really long time brain storming, I finally succeded so, here is the solution:
try
{
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "SQL Server database backup files|*.bak";
sd.Title = "Create Database Backup";
if (sd.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["project_name.Properties.Settings.project_nameConnectionString"].ConnectionString))
{
string sqlStmt = string.Format("backup database [" + System.Windows.Forms.Application.StartupPath + "\\dbname.mdf] to disk='{0}'",sd.FileName);
using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Backup Created Sucessfully");
}
}
}
}
catch (Exception)
{
MessageBox.Show("Backup Not Created");
}
资源:如何从我创建
这篇关于如何创建数据库备份,当数据库未存储在Microsoft SQL Server?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!