这是我备份数据库的代码
这些是我的数据库:
我得到了这个错误:
数据库'BakupDB'不存在。确保输入名称 正确。 BACKUP DATABASE异常终止。
我的网页代码:
public partial class Default2 : System.Web.UI.Page
{
string dbname = "BakupDB";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
//Mentioned Connection string make sure that user id and password sufficient previlages
sqlcon.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
//Enter destination directory where backup file stored
string destdir = "D:\\backupdb";
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database "+dbname+" to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
Response.Write("Backup database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
}
}
我错了什么?
答案 0 :(得分:1)
看起来您正在尝试使用User Instance。另外(与您的问题没有100%相关)我认为SQL Server Express 2012中不推荐使用此功能(自SQL Server 2008以来一直处于弃用状态)。
对不起。关于您的问题,以下内容可能对您有所帮助:
我想说Stack Overflow问题更接近于您尝试通过执行SQL命令实现的用例,但是如果您感兴趣或想要尝试不同的方法,则引用了SMO方式。根据SO问题,您的连接字符串显示为:
sqlcon.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
缺少Database=
部分,所以它可能应该是:
sqlcon.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True;Database=BakupDB";
答案 1 :(得分:0)
此代码对我有用:
private void button5_Click(object sender, EventArgs e)
{
try
{
string dlink= @"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\jsdb.mdf; Database=jsdb; User Instance=True; Integrated Security=True;Asynchronous Processing= True";
SqlConnection dcc = new SqlConnection(dlink);
dcc.Open();
string database = "jsdb";
string blc = textBox1.Text; //(Its the location to save the file)
string nm = "dbBackup";
string dt =DateTime.Today.ToShortDateString();
string sl = "BACKUP DATABASE "+database+" TO DISK = '"+blc+"\\"+nm+"-"+dt+".bak'" ;
SqlCommand cql = new SqlCommand(sl,dcc);
cql.ExecuteNonQuery();
MessageBox.Show("Database backup completed successfully..");
dcc.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}