1

这是我备份数据库的代码。
这些是我的数据库:
在此处输入图像描述

我得到了这个错误:

数据库“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!");
        }
    }
}

我错了什么?

4

2 回答 2

1

看起来您正在尝试使用User Instance。顺便说一句(与您的问题不是 100% 相关),我相信此功能在 SQL Server Express 2012 中已被弃用(并且自 SQL Server 2008 以来一直处于弃用路径)。

对不起旁边。关于您的问题,也许以下内容会对您有所帮助:

我会说 Stack Overflow 问题更接近您通过执行 SQL 命令尝试实现的用例,但如果您有兴趣或想尝试不同的方法,请参考 SMO 方式。根据 SO question,您的连接字符串似乎是:

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";
于 2013-03-21T16:43:51.953 回答
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); }
}
于 2020-01-15T16:00:23.833 回答