简体   繁体   English

从C#备份数据库

[英]Backup database from C#

I have a stored procedure that works fine when I run it when using Windows authentication. 我有一个存储过程,在使用Windows身份验证时运行该存储过程时效果很好。 If I run it as the standard website user it fails, I guessed it was a permissions thing. 如果我以标准网站用户身份运行它,它将失败,我猜测这是权限问题。 So I'm trying to add a script in that allows me to connect to the database from C# and run the backup using Windows auth. 因此,我试图在其中添加一个脚本,该脚本允许我从C#连接到数据库并使用Windows身份验证运行备份。

public bool BackUpDataBase()
{
    string connString = _country == Country.England ? _connectionStringSiteDbEngland : _connectionStringSiteDbScotland;

    try
    {
            using (SqlConnection conn = new SqlConnection(connString)) 
            {
                conn.Open();
                SqlCommand cmd  = new SqlCommand("BackupDB", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@BaseLocation", _serverBackupLocation));
                cmd.Parameters.Add(new SqlParameter("@BackupType", _backupType));
                cmd.ExecuteNonQuery();
                return true;
            }
    } 
    catch (Exception e)
    {
        //FAILED :(
        return false;
    }
}

I get a timeout error on cmd.ExecuteNonQuery(); 我在cmd.ExecuteNonQuery();上收到超时错误cmd.ExecuteNonQuery(); . The same connection string allows me to connect the the database to query a table here. 相同的连接字符串使我可以在此处连接数据库以查询表。

public bool IsScheduled()
{
        string archiveDB = _country == Country.England ? _englandArchiveDBName : _scotlandArchiveDBName;

        using (SqlConnection conn = new SqlConnection(_country == Country.England ? _connectionStringSiteDbEngland : _connectionStringSiteDbScotland)) 
        {
            conn.Open();
            SqlCommand cmd  = new SqlCommand(SQLToCheckSchedule(), conn);
            cmd.CommandType = CommandType.Text;

            int rows = 0;

            using (SqlDataReader rdr = cmd.ExecuteReader()) 
            {
               while (rdr.Read())
               {
                    rows++;
               }
            }  

            conn.Close();

            return rows > 0;
        }
}

Any ideas? 有任何想法吗?

Your database backup process simply takes too long compared to a regular table query. 与常规表查询相比,您的数据库备份过程仅花费太长时间。 You can set the command timeout via the SqlCommand.CommandTimeout property 您可以通过SqlCommand.CommandTimeout属性设置命令超时

cmd.CommandTimeout = 1000; //This is in seconds
cmd.ExecuteNonQuery();

The default is 30 seconds. 默认值为30秒。 You can also set it to 0 so that it would wait indefinitely. 您也可以将其设置为0,以使其无限期等待。 However, this is a bit dangerous as this may lock your site/app. 但是,这样做有点危险,因为这可能会锁定您的网站/应用程序。 You may want to set your backup processes somewhere else instead, such as a scheduled task. 您可能希望将备份过程设置在其他地方,例如计划任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM