用C# Windows服务备份数据库
第一步:
新建一个Windows服务
添加Microsoft SQLDMO Object Library引用
使用Timer定时
public partial class Service1 : ServiceBase
{
Timer timer1 = new Timer();
public Service1()
{
InitializeComponent();
timer1.Interval = 60000;//3600000;
timer1.Enabled = true;
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private void timer1_Tick(object sender, EventArgs e)
{
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect(".", "sa", "sa");//服务器名、账号、密码
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = "cmsTest";
oBackup.Files = @"d:\cmsTest.bak";
oBackup.BackupSetName = "cmsTest";
oBackup.BackupSetDescription = "数据库备份";
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
}
catch
{
throw;
}
finally
{
oSQLServer.DisConnect();
} }
}
{
Timer timer1 = new Timer();
public Service1()
{
InitializeComponent();
timer1.Interval = 60000;//3600000;
timer1.Enabled = true;
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
private void timer1_Tick(object sender, EventArgs e)
{
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect(".", "sa", "sa");//服务器名、账号、密码
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = "cmsTest";
oBackup.Files = @"d:\cmsTest.bak";
oBackup.BackupSetName = "cmsTest";
oBackup.BackupSetDescription = "数据库备份";
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
}
catch
{
throw;
}
finally
{
oSQLServer.DisConnect();
} }
}
然后在设计视图添加安装程序
这时项目中就添加了一个新类 ProjectInstaller 和两个安装组件 ServiceProcessInstaller 和 ServiceInstaller,并且服务的属性值被复制到组件。
若要确定如何启动服务,请单击 ServiceInstaller 组件并将 StartType 属性设置为适当的值。
ü Manual 服务安装后,必须手动启动。
ü Automatic 每次计算机重新启动时,服务都会自动启动。
ü Disabled 服务无法启动。
将serviceProcessInstaller类的Account属性改为 LocalSystem
这样,不论是以哪个用户登录的系统,服务总会启动。
再生成服务程序
在bin\Debug目录下生成了对应的**.exe文件
新建一个in.bat和一个un.bat文件里面内容分别是
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe **.exe
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe **.exe /u
运行in.bat安装服务,运行un.bat卸载服务