备份:
string sql=null;
if( conn.State == ConnectionState.Open)
conn.Close();
conn.ConnectionString = ConnectionString;
conn.Open();
string nowpath=Application.StartupPath;
sql="backup database mydb to disk='"+nowpath+"\\数据备份文件(不要删除).dll"+"' with format,name='Full Backup of TradeDb/SQL'";
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("成功备份数据!备份记录为:"+nowpath+"\\数据备份文件(不要删除).dll"," 成功了!", MessageBoxButtons.OK, MessageBoxIcon.Information );
}
catch(Exception err)
{
MessageBox.Show("出现错误,请与作者联系!"+err.ToString() ,"出错了!",MessageBoxButtons.OK ,MessageBoxIcon.Question );
}
finally
{
conn.Close();
this.Close();
}
还原:
string sql=null;
if( conn.State == ConnectionState.Open)
conn.Close();
ConnectionString = "data source="+Form1.HostName+";initial catalog=master;persist security info=False;user id=sa;pwd="+Form1.DataPass+";";
conn.ConnectionString=ConnectionString;
conn.Open();
try
{
string nowpath=Application.StartupPath;
//进入master
sql="use master";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
try
{
//执行存储过程杀掉其它进程
sql="exec killspid 'mydb'";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
finally
{
FileInfo backupdata = new FileInfo(nowpath+"\\数据备份文件(不要删除).dll");
if (backupdata.Exists)
{
sql="restore database mydb from disk='"+nowpath+"\\数据备份文件(不要删除).dll"+"' with recovery";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("成功恢复数据!从"+nowpath+"\\数据备份文件(不要删除).dll 中恢复"," 成功了!", MessageBoxButtons.OK, MessageBoxIcon.Information );
}
else
{
MessageBox.Show("你可能以前没有备份过数据库!数据备份文件(不要删除).dll 不存在!"," 错误!", MessageBoxButtons.OK, MessageBoxIcon.Information );
}
}
}
catch(Exception err)
{
MessageBox.Show("出现错误,请对数据库端进行正确配置!"+err.ToString() ,"出错了!",MessageBoxButtons.OK ,MessageBoxIcon.Question );
}
finally
{
conn.Close();
this.Close();
}
忘了,要在数据库中放一段杀进程的代码,存为存储过程
create proc killspid (@dbname varchar(20))
as
begin
declare @sql nvarchar(500)
declare @spid int
set @sql='declare getspid cursor for
select spid from sysprocesses where dbid=db_id('''+@dbname+''')'
exec (@sql)
open getspid
fetch next from getspid into @spid
while @@fetch_status < >-1
begin
exec('kill '+@spid)
fetch next from getspid into @spid
end
close getspid
deallocate getspid
end