怎样才能实现对数据库的还原呢?麻烦写下前台和后台的代码。数据库名字为student。
15 个解决方案
#1
你把有关连接数据库的进程全部关掉在运行你的程序 肯定也就还原了
你的数据库正在使用 怎么进行操作呢?
你的数据库正在使用 怎么进行操作呢?
#2
取得数据库服务器列表:
public ArrayList GetServerList()
{
ArrayList alServers = new ArrayList() ;
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass() ;
try
{
SQLDMO.NameList serverList = sqlApp.ListAvailableSQLServers() ;
for(int i = 1;i<= serverList.Count;i++)
{
alServers.Add(serverList.Item(i)) ;
}
}
catch(Exception e)
{
throw(new Exception("取数据库服务器列表出错:"+e.Message)) ;
}
finally
{
sqlApp.Quit() ;
}
return alServers ;
}
取得指定数据库服务器的数据库列表
public ArrayList GetDbList(string strServerName,string strUserName,string strPwd)
{
ServerName = strServerName ;
UserName = strUserName ;
Password = strPwd ;
ArrayList alDbs = new ArrayList() ;
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass() ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
foreach(SQLDMO.Database db in svr.Databases)
{
if(db.Name!=null)
alDbs.Add(db.Name) ;
}
}
catch(Exception e)
{
throw(new Exception("连接数据库出错:"+e.Message)) ;
}
finally
{
svr.DisConnect() ;
sqlApp.Quit() ;
}
return alDbs ;
}
2. 数据库的备份和实时进度显示代码:
public bool BackUPDB(string strDbName,string strFileName, ProgressBar pgbMain)
{
PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
SQLDMO.Backup bak = new SQLDMO.BackupClass();
bak.Action = 0 ;
bak.Initialize = true ;
SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
bak.PercentComplete += pceh;
bak.Files = strFileName;
bak.Database = strDbName;
bak.SQLBackup(svr);
return true ;
}
catch(Exception err)
{
throw(new Exception("备份数据库失败"+err.Message)) ;
}
finally
{
svr.DisConnect() ;
}
}
private void Step(string message,int percent)
{
PBar.Value = percent ;
}
其中,这两个语句实现了进度的实时显示:
SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
bak.PercentComplete += pceh;
Step就是上面private void Step(string message,int percent) 的方法名称,它用来显示进度条的当前进度。
3. 数据库的恢复和杀死进程的代码:
public bool RestoreDB(string strDbName,string strFileName, ProgressBar pgbMain)
{
PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
svr.KillProcess(lPID) ;
}
SQLDMO.Restore res = new SQLDMO.RestoreClass() ;
res.Action = 0 ;
SQLDMO.RestoreSink_PercentCompleteEventHandler pceh = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);
res.PercentComplete += pceh;
res.Files = strFileName ;
res.Database = strDbName ;
res.ReplaceDatabase = true ;
res.SQLRestore(svr) ;
return true ;
}
catch(Exception err)
{
throw(new Exception("恢复数据库失败,请关闭所有和该数据库连接的程序!"+err.Message)) ;
}
finally
{
svr.DisConnect() ;
}
}
其中这个语句取得了所有的进程列表:
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
下面的语句找到和要恢复数据库相关的进程并杀死:
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
svr.KillProcess(lPID) ;
}
运行的前提是你的数据库所有进程 关闭。。。
#3
还原时,先杀掉正在使用的进程,然后再进行还原操作,用上面的sqldmo操作比较好的,人家已经封装好的
#4
强悍.........
#5
杀死ID
CREATE proc RestoreDb @bkfile nvarchar(1000),@dbname sysname='',@dbpath nvarchar(260)='',@retype nvarchar(10)='DB',@filenumber int=1, @overexist bit=1,@killuser bit=1
as declare @sql varchar(8000) if isnull(@dbname,'')=''select @sql=reverse(@bkfile),@sql=case when charindex('.',@sql)=0 then @sql else substring(@sql,charindex('.',@sql)+1,1000) end ,@sql=case when charindex('\',@sql)=0 then @sql else left(@sql,charindex('\',@sql)-1) end,@dbname=reverse(@sql)
set @sql='restore '+case @retype when 'LOG' then 'log ' else 'database ' end+@dbname+' from disk='''+@bkfile+''''+' with file='+cast(@filenumber as varchar) +case when @overexist=1 and @retype in('DB','DBNOR') then ',replace' else '' end +case @retype when 'DBNOR' then ',NORECOVERY' else ',RECOVERY' end
print @sql
if @overexist=1 and @killuser=1
begin declare @spid varchar(20) declare #spid cursor for select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname) open #spid fetch next from #spid into @spid while @@fetch_status=0 begin exec('kill '+@spid) fetch next from #spid into @spid End close #spid deallocate #spid End
exec (@sql)
CREATE proc RestoreDb @bkfile nvarchar(1000),@dbname sysname='',@dbpath nvarchar(260)='',@retype nvarchar(10)='DB',@filenumber int=1, @overexist bit=1,@killuser bit=1
as declare @sql varchar(8000) if isnull(@dbname,'')=''select @sql=reverse(@bkfile),@sql=case when charindex('.',@sql)=0 then @sql else substring(@sql,charindex('.',@sql)+1,1000) end ,@sql=case when charindex('\',@sql)=0 then @sql else left(@sql,charindex('\',@sql)-1) end,@dbname=reverse(@sql)
set @sql='restore '+case @retype when 'LOG' then 'log ' else 'database ' end+@dbname+' from disk='''+@bkfile+''''+' with file='+cast(@filenumber as varchar) +case when @overexist=1 and @retype in('DB','DBNOR') then ',replace' else '' end +case @retype when 'DBNOR' then ',NORECOVERY' else ',RECOVERY' end
print @sql
if @overexist=1 and @killuser=1
begin declare @spid varchar(20) declare #spid cursor for select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname) open #spid fetch next from #spid into @spid while @@fetch_status=0 begin exec('kill '+@spid) fetch next from #spid into @spid End close #spid deallocate #spid End
exec (@sql)
#6
#7
#8
#9
因为正在使用呢.
#10
请问#5楼
那些代码写在哪啊?
页面上吗。还是在sql2005查询分析器里面写
那些代码写在哪啊?
页面上吗。还是在sql2005查询分析器里面写
#11
5楼贴的是C#的代码.
可以从页面上面写个事件触发来引用啦.
可以从页面上面写个事件触发来引用啦.
#12
原来的库删掉,然后还原,还原的时候还用原来库的名字
#13
winform里面的 回复按钮下面代码
private void btnDataInit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要使用数据初始化功能吗?程序安装之后的生成的数据将被清除", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + System.Windows.Forms.Application.StartupPath + "\\BackUp\\LMS.BAK" + "'";
try
{
cmdRT.ExecuteNonQuery();
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化完成\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化完成!程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化失败!(" + ex.ToString().Trim() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
finally
{
conn.Close();
}
}
private void btnDataInit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要使用数据初始化功能吗?程序安装之后的生成的数据将被清除", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + System.Windows.Forms.Application.StartupPath + "\\BackUp\\LMS.BAK" + "'";
try
{
cmdRT.ExecuteNonQuery();
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化完成\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化完成!程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化失败!(" + ex.ToString().Trim() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
finally
{
conn.Close();
}
}
#14
刚才我发的是数据库初始化按钮下面的,这个是恢复数据按钮下的代码
private void btnImp_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "打开备份文件";
openFileDialog1.Filter = "备份文件(*.bak)|*.bak";
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
//给数据恢复一个起始的默认路径
openFileDialog1.InitialDirectory = directoryPath;
/***********************************************************************/
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
if (MessageBox.Show("确定要使用数据恢复吗?备份时间之后的数据会丢失!\r\n恢复结束后程序将重新启动。是否继续?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
//string strConnectstring = "Server=" + this.textBox2.Text.Trim() + ";Database=Master;User ID=" + this.textBox4.Text.Trim() + ";Password=" + textBox5.Text.Trim() + ";";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + openFileDialog1.FileName + "'";
try
{
this.Cursor = Cursors.Default;
cmdRT.ExecuteNonQuery();
//MessageBox.Show("数据恢复成功!\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复成功!程序将重新启动。";//启动参数 ExeName Message
p.Start();//启动
this.ParentForm.Dispose();
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据恢复失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复失败!(" + ex.ToString() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
}
finally
{
//this.Cursor = Cursors.Default;
conn.Close();
}
}
private void btnImp_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "打开备份文件";
openFileDialog1.Filter = "备份文件(*.bak)|*.bak";
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
//给数据恢复一个起始的默认路径
openFileDialog1.InitialDirectory = directoryPath;
/***********************************************************************/
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
if (MessageBox.Show("确定要使用数据恢复吗?备份时间之后的数据会丢失!\r\n恢复结束后程序将重新启动。是否继续?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
//string strConnectstring = "Server=" + this.textBox2.Text.Trim() + ";Database=Master;User ID=" + this.textBox4.Text.Trim() + ";Password=" + textBox5.Text.Trim() + ";";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + openFileDialog1.FileName + "'";
try
{
this.Cursor = Cursors.Default;
cmdRT.ExecuteNonQuery();
//MessageBox.Show("数据恢复成功!\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复成功!程序将重新启动。";//启动参数 ExeName Message
p.Start();//启动
this.ParentForm.Dispose();
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据恢复失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复失败!(" + ex.ToString() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
}
finally
{
//this.Cursor = Cursors.Default;
conn.Close();
}
}
#15
这个是备份数据库按钮下的代码
private void btnExp_Click(object sender, EventArgs e)
{
string filename;
filename = DateTime.Now.ToString("yyyy/MM/dd hhmmss") + "JY_DATA.bak";
saveFileDialog1.FileName = filename;
//saveFileDialog1.Filter = "Excel文档|.xls";
saveFileDialog1.Title = "备份存放位置";
saveFileDialog1.Filter = "备份文件(*.bak)|*.bak";//excel files(*.xls)|*.xls|All files(*.*)|*.*
saveFileDialog1.FilterIndex = 0;
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
/********************************************************************************/
saveFileDialog1.InitialDirectory = directoryPath; //upd by chenshihu 20101122
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string path = saveFileDialog1.FileName;
string strConnectstring = "Server=.;Database=LMS;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
SqlCommand cmdBK = new SqlCommand();
cmdBK.CommandType = CommandType.Text;
cmdBK.Connection = conn;
cmdBK.CommandText = @"backup database LMS to disk='" + path + "' with init";
try
{
conn.Open();
cmdBK.ExecuteNonQuery();
this.Cursor = Cursors.Default;
MessageBox.Show("备份成功!", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
MessageBox.Show("备份失败!(" + ex.ToString() + ")", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();
conn.Dispose();
}
}
我发完了,希望能帮你解决问题。
private void btnExp_Click(object sender, EventArgs e)
{
string filename;
filename = DateTime.Now.ToString("yyyy/MM/dd hhmmss") + "JY_DATA.bak";
saveFileDialog1.FileName = filename;
//saveFileDialog1.Filter = "Excel文档|.xls";
saveFileDialog1.Title = "备份存放位置";
saveFileDialog1.Filter = "备份文件(*.bak)|*.bak";//excel files(*.xls)|*.xls|All files(*.*)|*.*
saveFileDialog1.FilterIndex = 0;
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
/********************************************************************************/
saveFileDialog1.InitialDirectory = directoryPath; //upd by chenshihu 20101122
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string path = saveFileDialog1.FileName;
string strConnectstring = "Server=.;Database=LMS;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
SqlCommand cmdBK = new SqlCommand();
cmdBK.CommandType = CommandType.Text;
cmdBK.Connection = conn;
cmdBK.CommandText = @"backup database LMS to disk='" + path + "' with init";
try
{
conn.Open();
cmdBK.ExecuteNonQuery();
this.Cursor = Cursors.Default;
MessageBox.Show("备份成功!", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
MessageBox.Show("备份失败!(" + ex.ToString() + ")", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();
conn.Dispose();
}
}
我发完了,希望能帮你解决问题。
#1
你把有关连接数据库的进程全部关掉在运行你的程序 肯定也就还原了
你的数据库正在使用 怎么进行操作呢?
你的数据库正在使用 怎么进行操作呢?
#2
取得数据库服务器列表:
public ArrayList GetServerList()
{
ArrayList alServers = new ArrayList() ;
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass() ;
try
{
SQLDMO.NameList serverList = sqlApp.ListAvailableSQLServers() ;
for(int i = 1;i<= serverList.Count;i++)
{
alServers.Add(serverList.Item(i)) ;
}
}
catch(Exception e)
{
throw(new Exception("取数据库服务器列表出错:"+e.Message)) ;
}
finally
{
sqlApp.Quit() ;
}
return alServers ;
}
取得指定数据库服务器的数据库列表
public ArrayList GetDbList(string strServerName,string strUserName,string strPwd)
{
ServerName = strServerName ;
UserName = strUserName ;
Password = strPwd ;
ArrayList alDbs = new ArrayList() ;
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass() ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
foreach(SQLDMO.Database db in svr.Databases)
{
if(db.Name!=null)
alDbs.Add(db.Name) ;
}
}
catch(Exception e)
{
throw(new Exception("连接数据库出错:"+e.Message)) ;
}
finally
{
svr.DisConnect() ;
sqlApp.Quit() ;
}
return alDbs ;
}
2. 数据库的备份和实时进度显示代码:
public bool BackUPDB(string strDbName,string strFileName, ProgressBar pgbMain)
{
PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
SQLDMO.Backup bak = new SQLDMO.BackupClass();
bak.Action = 0 ;
bak.Initialize = true ;
SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
bak.PercentComplete += pceh;
bak.Files = strFileName;
bak.Database = strDbName;
bak.SQLBackup(svr);
return true ;
}
catch(Exception err)
{
throw(new Exception("备份数据库失败"+err.Message)) ;
}
finally
{
svr.DisConnect() ;
}
}
private void Step(string message,int percent)
{
PBar.Value = percent ;
}
其中,这两个语句实现了进度的实时显示:
SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
bak.PercentComplete += pceh;
Step就是上面private void Step(string message,int percent) 的方法名称,它用来显示进度条的当前进度。
3. 数据库的恢复和杀死进程的代码:
public bool RestoreDB(string strDbName,string strFileName, ProgressBar pgbMain)
{
PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
svr.Connect(ServerName,UserName,Password) ;
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
svr.KillProcess(lPID) ;
}
SQLDMO.Restore res = new SQLDMO.RestoreClass() ;
res.Action = 0 ;
SQLDMO.RestoreSink_PercentCompleteEventHandler pceh = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);
res.PercentComplete += pceh;
res.Files = strFileName ;
res.Database = strDbName ;
res.ReplaceDatabase = true ;
res.SQLRestore(svr) ;
return true ;
}
catch(Exception err)
{
throw(new Exception("恢复数据库失败,请关闭所有和该数据库连接的程序!"+err.Message)) ;
}
finally
{
svr.DisConnect() ;
}
}
其中这个语句取得了所有的进程列表:
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
下面的语句找到和要恢复数据库相关的进程并杀死:
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
svr.KillProcess(lPID) ;
}
运行的前提是你的数据库所有进程 关闭。。。
#3
还原时,先杀掉正在使用的进程,然后再进行还原操作,用上面的sqldmo操作比较好的,人家已经封装好的
#4
强悍.........
#5
杀死ID
CREATE proc RestoreDb @bkfile nvarchar(1000),@dbname sysname='',@dbpath nvarchar(260)='',@retype nvarchar(10)='DB',@filenumber int=1, @overexist bit=1,@killuser bit=1
as declare @sql varchar(8000) if isnull(@dbname,'')=''select @sql=reverse(@bkfile),@sql=case when charindex('.',@sql)=0 then @sql else substring(@sql,charindex('.',@sql)+1,1000) end ,@sql=case when charindex('\',@sql)=0 then @sql else left(@sql,charindex('\',@sql)-1) end,@dbname=reverse(@sql)
set @sql='restore '+case @retype when 'LOG' then 'log ' else 'database ' end+@dbname+' from disk='''+@bkfile+''''+' with file='+cast(@filenumber as varchar) +case when @overexist=1 and @retype in('DB','DBNOR') then ',replace' else '' end +case @retype when 'DBNOR' then ',NORECOVERY' else ',RECOVERY' end
print @sql
if @overexist=1 and @killuser=1
begin declare @spid varchar(20) declare #spid cursor for select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname) open #spid fetch next from #spid into @spid while @@fetch_status=0 begin exec('kill '+@spid) fetch next from #spid into @spid End close #spid deallocate #spid End
exec (@sql)
CREATE proc RestoreDb @bkfile nvarchar(1000),@dbname sysname='',@dbpath nvarchar(260)='',@retype nvarchar(10)='DB',@filenumber int=1, @overexist bit=1,@killuser bit=1
as declare @sql varchar(8000) if isnull(@dbname,'')=''select @sql=reverse(@bkfile),@sql=case when charindex('.',@sql)=0 then @sql else substring(@sql,charindex('.',@sql)+1,1000) end ,@sql=case when charindex('\',@sql)=0 then @sql else left(@sql,charindex('\',@sql)-1) end,@dbname=reverse(@sql)
set @sql='restore '+case @retype when 'LOG' then 'log ' else 'database ' end+@dbname+' from disk='''+@bkfile+''''+' with file='+cast(@filenumber as varchar) +case when @overexist=1 and @retype in('DB','DBNOR') then ',replace' else '' end +case @retype when 'DBNOR' then ',NORECOVERY' else ',RECOVERY' end
print @sql
if @overexist=1 and @killuser=1
begin declare @spid varchar(20) declare #spid cursor for select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname) open #spid fetch next from #spid into @spid while @@fetch_status=0 begin exec('kill '+@spid) fetch next from #spid into @spid End close #spid deallocate #spid End
exec (@sql)
#6
#7
#8
#9
因为正在使用呢.
#10
请问#5楼
那些代码写在哪啊?
页面上吗。还是在sql2005查询分析器里面写
那些代码写在哪啊?
页面上吗。还是在sql2005查询分析器里面写
#11
5楼贴的是C#的代码.
可以从页面上面写个事件触发来引用啦.
可以从页面上面写个事件触发来引用啦.
#12
原来的库删掉,然后还原,还原的时候还用原来库的名字
#13
winform里面的 回复按钮下面代码
private void btnDataInit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要使用数据初始化功能吗?程序安装之后的生成的数据将被清除", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + System.Windows.Forms.Application.StartupPath + "\\BackUp\\LMS.BAK" + "'";
try
{
cmdRT.ExecuteNonQuery();
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化完成\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化完成!程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化失败!(" + ex.ToString().Trim() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
finally
{
conn.Close();
}
}
private void btnDataInit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要使用数据初始化功能吗?程序安装之后的生成的数据将被清除", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + System.Windows.Forms.Application.StartupPath + "\\BackUp\\LMS.BAK" + "'";
try
{
cmdRT.ExecuteNonQuery();
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化完成\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化完成!程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据初始化失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据初始化失败!(" + ex.ToString().Trim() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
return;
}
finally
{
conn.Close();
}
}
#14
刚才我发的是数据库初始化按钮下面的,这个是恢复数据按钮下的代码
private void btnImp_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "打开备份文件";
openFileDialog1.Filter = "备份文件(*.bak)|*.bak";
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
//给数据恢复一个起始的默认路径
openFileDialog1.InitialDirectory = directoryPath;
/***********************************************************************/
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
if (MessageBox.Show("确定要使用数据恢复吗?备份时间之后的数据会丢失!\r\n恢复结束后程序将重新启动。是否继续?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
//string strConnectstring = "Server=" + this.textBox2.Text.Trim() + ";Database=Master;User ID=" + this.textBox4.Text.Trim() + ";Password=" + textBox5.Text.Trim() + ";";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + openFileDialog1.FileName + "'";
try
{
this.Cursor = Cursors.Default;
cmdRT.ExecuteNonQuery();
//MessageBox.Show("数据恢复成功!\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复成功!程序将重新启动。";//启动参数 ExeName Message
p.Start();//启动
this.ParentForm.Dispose();
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据恢复失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复失败!(" + ex.ToString() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
}
finally
{
//this.Cursor = Cursors.Default;
conn.Close();
}
}
private void btnImp_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "打开备份文件";
openFileDialog1.Filter = "备份文件(*.bak)|*.bak";
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
//给数据恢复一个起始的默认路径
openFileDialog1.InitialDirectory = directoryPath;
/***********************************************************************/
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
if (MessageBox.Show("确定要使用数据恢复吗?备份时间之后的数据会丢失!\r\n恢复结束后程序将重新启动。是否继续?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string strConnectstring = "Server=.;User ID=sa;Password=;";
//string strConnectstring = "Server=" + this.textBox2.Text.Trim() + ";Database=Master;User ID=" + this.textBox4.Text.Trim() + ";Password=" + textBox5.Text.Trim() + ";";
SqlConnection conn = new SqlConnection(strConnectstring);
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM dbo.sysprocesses ,dbo.sysdatabases WHERE dbo.sysprocesses.dbid=dbo.sysdatabases.dbid AND dbo.sysdatabases.Name='LMS'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database LMS from disk='" + openFileDialog1.FileName + "'";
try
{
this.Cursor = Cursors.Default;
cmdRT.ExecuteNonQuery();
//MessageBox.Show("数据恢复成功!\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复成功!程序将重新启动。";//启动参数 ExeName Message
p.Start();//启动
this.ParentForm.Dispose();
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
//MessageBox.Show("数据恢复失败(" + ex.ToString() + ")\r\n请重启程序。", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "Restar.exe";//需要启动的程序名
p.StartInfo.WorkingDirectory = Application.StartupPath;
p.StartInfo.Arguments = "LMS.exe 数据恢复失败!(" + ex.ToString() + ")程序将重新启动。";//启动参数
p.Start();//启动
this.ParentForm.Dispose();
}
finally
{
//this.Cursor = Cursors.Default;
conn.Close();
}
}
#15
这个是备份数据库按钮下的代码
private void btnExp_Click(object sender, EventArgs e)
{
string filename;
filename = DateTime.Now.ToString("yyyy/MM/dd hhmmss") + "JY_DATA.bak";
saveFileDialog1.FileName = filename;
//saveFileDialog1.Filter = "Excel文档|.xls";
saveFileDialog1.Title = "备份存放位置";
saveFileDialog1.Filter = "备份文件(*.bak)|*.bak";//excel files(*.xls)|*.xls|All files(*.*)|*.*
saveFileDialog1.FilterIndex = 0;
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
/********************************************************************************/
saveFileDialog1.InitialDirectory = directoryPath; //upd by chenshihu 20101122
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string path = saveFileDialog1.FileName;
string strConnectstring = "Server=.;Database=LMS;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
SqlCommand cmdBK = new SqlCommand();
cmdBK.CommandType = CommandType.Text;
cmdBK.Connection = conn;
cmdBK.CommandText = @"backup database LMS to disk='" + path + "' with init";
try
{
conn.Open();
cmdBK.ExecuteNonQuery();
this.Cursor = Cursors.Default;
MessageBox.Show("备份成功!", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
MessageBox.Show("备份失败!(" + ex.ToString() + ")", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();
conn.Dispose();
}
}
我发完了,希望能帮你解决问题。
private void btnExp_Click(object sender, EventArgs e)
{
string filename;
filename = DateTime.Now.ToString("yyyy/MM/dd hhmmss") + "JY_DATA.bak";
saveFileDialog1.FileName = filename;
//saveFileDialog1.Filter = "Excel文档|.xls";
saveFileDialog1.Title = "备份存放位置";
saveFileDialog1.Filter = "备份文件(*.bak)|*.bak";//excel files(*.xls)|*.xls|All files(*.*)|*.*
saveFileDialog1.FilterIndex = 0;
/**** ADD By chenshihu 20101122 如果程序安装路径中不存在BackUp文件夹,则创建 ****/
string directoryPath = System.Windows.Forms.Application.StartupPath + "\\BackUp";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
/********************************************************************************/
saveFileDialog1.InitialDirectory = directoryPath; //upd by chenshihu 20101122
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
this.Cursor = Cursors.WaitCursor;
string path = saveFileDialog1.FileName;
string strConnectstring = "Server=.;Database=LMS;User ID=sa;Password=;";
SqlConnection conn = new SqlConnection(strConnectstring);
SqlCommand cmdBK = new SqlCommand();
cmdBK.CommandType = CommandType.Text;
cmdBK.Connection = conn;
cmdBK.CommandText = @"backup database LMS to disk='" + path + "' with init";
try
{
conn.Open();
cmdBK.ExecuteNonQuery();
this.Cursor = Cursors.Default;
MessageBox.Show("备份成功!", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
this.Cursor = Cursors.Default;
MessageBox.Show("备份失败!(" + ex.ToString() + ")", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();
conn.Dispose();
}
}
我发完了,希望能帮你解决问题。