制作msi安装文件的同时,还原备份的sql server 数据库。
在http://blog.csdn.net/xbfitliu/article/details/8507900中自定义安装类中(8、自定安装类获取自定义界面输入的数据)
添加还原Sql Server数据库操作。下面方法就是在安装的过程中增加还原备份的Sql Server数据库。
private void RestoreDB(string dbServer, string uName, string pwd, string targetdir, string dbName, string dbInstallPath)
{
File.AppendAllText(Path.Combine(targetdir, "log.txt"), "开始还原备份数据库……" + Environment.NewLine);
string strConn = string.Format("Data Source = {0};DataBase=master;User ID = {1};PWD={2}",
dbServer, uName, pwd);
//数据恢复语句:restore database 数据库名 from disk='保存路径/dbName.bak' WITH MOVE 'dbName_Data' TO 'c:/tcomcrm20041217.mdf', --数据文件还原后存放的新位置
//dbName_Data为数据库逻辑文件名可以用RESTORE FILELISTONLY FROM DISK = '文件路径'
StringBuilder sBuilder = new StringBuilder();
sBuilder.AppendFormat(@"RESTORE DATABASE {0} FROM DISK='{1}' ", dbName, Path.Combine(targetdir, string.Format("{0}.bak", dbName)));
sBuilder.AppendFormat(@" WITH MOVE '{0}' TO '{1}' ", dbName, Path.Combine(dbInstallPath, string.Format("{0}.mdf", dbName)));
sBuilder.AppendFormat(@" ,MOVE '{0}_log' TO '{1}' ", dbName, Path.Combine(dbInstallPath, string.Format("{0}.ldf", dbName)));
SqlConnection conn = new SqlConnection(strConn);
try
{
conn.Open();
File.AppendAllText(Path.Combine(targetdir, "log.txt"), "打开连接……" + Environment.NewLine);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sBuilder.ToString();
File.AppendAllText(Path.Combine(targetdir, "log.txt"), sBuilder.ToString() + Environment.NewLine);
cmd.ExecuteNonQuery();
File.AppendAllText(Path.Combine(targetdir, "log.txt"), "执行还原操作……" + Environment.NewLine);
}
catch (Exception ex)
{
File.AppendAllText(Path.Combine(targetdir, "log.txt"), ex.Message + Environment.NewLine);
throw new Exception("还原数据库出错");
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
File.AppendAllText(Path.Combine(targetdir, "log.txt"), "释放资源。" + Environment.NewLine);
}
}
}
在做类似操作,个人觉的记录日志是个很好方法,这样可以清楚的知道在哪一步出现了问题。代码中还原数据库要使用到备份数据库的逻辑文件名,否则还原出错。如果不知道可以通过RESTORE FILELISTONLY FROM DISK = '文件路径'。这样就可以获取到备份文件的逻辑文件名。
到此,安装包中还原数据库就完成了。