如何通过 C# 动态备份 Sql 数据库?
咨询区
-
kaiz.net
我想写段代码来备份我的 Sql Server 2008
数据库,请问大家有什么好的方法吗?
回答区
-
Stacked
你可以用代码去执行 BACKUP DATABASE ... TO DISK
命令,比如下面这样,先配置下config。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI;" Timeout=30" />
</connectionStrings>
<appSettings>
<add key="BackupFolder" value="C:/temp/"/>
</appSettings>
</configuration>
然后就可以编码了。
// read connectionstring from config file
var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
// read backup folder from config file ("C:/temp/")
var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);
// set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
var backupFileName = String.Format("{0}{1}-{2}.bak",
backupFolder, sqlConStrBuilder.InitialCatalog,
DateTime.Now.ToString("yyyy-MM-dd"));
using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
{
var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'",
sqlConStrBuilder.InitialCatalog, backupFileName);
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
-
Prashant Manjule
对于 SqlServer 的备份和恢复,完全可以使用自带的 SqlCmd
命令,接下来就是用 C#
和 SqlCmd
互动就行了。
-
备份
SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
-
恢复
SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
然后我们通过 Process
启动 bat 脚本即可。
FileInfo file = new FileInfo("DB\\batfile.bat");
Process process = new Process();
process.StartInfo.FileName = file.FullName;
process.StartInfo.Arguments = @"-X";
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false; //Changed Line
process.StartInfo.RedirectStandardOutput = true; //Changed Line
process.Start();
string output = process.StandardOutput.ReadToEnd(); //Changed Line
process.WaitForExit(); //Moved Line
点评区
如果要备份DB,一般用数据库的计划任务,如果一定要通过代码实现,我觉得用 SqlCmd
工具更适合。