1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 在ASP.NET中备份和还原数据库

在ASP.NET中备份和还原数据库

时间:2022-09-22 21:38:00

相关推荐

在ASP.NET中备份和还原数据库

昨天看了《C#项目实录》中的进销存管理系统,和其他书里讲的案例一样,无非也就是数据库增删查改,但是这个进销存系统中有一个备份和还原数据库的功能,蛮有兴趣的,看了一下代码,原来如此,也就是通过SQL语句来进行备份和还原数据库,SQL语句如下:

Sql代码 --备份数据库backupdatabasedb_CSManagetodisk='c:\backup.bak'--还原数据库,必须先备份该数据库的日志文件到原先的备份文件中backuplogdb_CSManagetodisk='c:\backup.bak'restoredatabasedb_CSManagefromdisk='c:\backup.bak'

其中db_CSManage是数据库名称,disk后的路径即是备份文件存储的路径。

知道了SQL语句,那么在.NET代码中就容易多了,备份的.NET代码如下:

C#代码 try{if(txtPath.Text!=""&&txtName122.Text!=""){getSqlConnectiongeCon=newgetSqlConnection();SqlConnectioncon=geCon.GetCon();stringstrBacl="backupdatabasedb_CSManagetodisk='"+txtPath.Text.Trim()+"\\"+txtName.Text.Trim()+".bak'";SqlCommandCmd=newSqlCommand(strBacl,con);if(Cmd.ExecuteNonQuery()!=0){MessageBox.Show("数据备份成功!","提示框",MessageBoxButtons.OK,MessageBoxIcon.Information);this.Close();}else{MessageBox.Show("数据备份失败!","提示框",MessageBoxButtons.OK,MessageBoxIcon.Information);}}else{MessageBox.Show("请填写备份的正确位置及文件名!","提示框",MessageBoxButtons.OK,MessageBoxIcon.Information);}//end}catch(Exceptionee){MessageBox.Show(ee.Message.ToString());}

以下是还原数据库的代码,在示例中发现开头得先删除与该数据库相关的进程,然后在还原之前得先把数据库日志备份到开始的备份文件中,然后才还原备份文件,要不然会出错的,代码如下:

C#代码 if(textPaht.Text!=""){getSqlConnectiongeCon=newgetSqlConnection();SqlConnectioncon=geCon.GetCon();if(con.State==ConnectionState.Open){con.Close();}stringDateStr="DataSource=niunan\\sqlexpress;Database=master;Userid=sa;PWD=123456";SqlConnectionconn=newSqlConnection(DateStr);conn.Open();//-------------------杀掉所有连接db_CSManage数据库的进程--------------stringstrSQL="selectspidfrommaster..sysprocesseswheredbid=db_id('db_CSManage')";SqlDataAdapterDa=newSqlDataAdapter(strSQL,conn);DataTablespidTable=newDataTable();Da.Fill(spidTable);SqlCommandCmd=newSqlCommand();mandType=CommandType.Text;Cmd.Connection=conn;for(intiRow=0;iRow<=spidTable.Rows.Count-1;iRow++){mandText="kill"+spidTable.Rows[iRow][0].ToString();//强行关闭用户进程Cmd.ExecuteNonQuery();}conn.Close();conn.Dispose();//--------------------------------------------------------------------SqlConnectionsqlcon=newSqlConnection(DateStr);sqlcon.Open();stringsql="backuplogdb_CSManagetodisk='"+textPaht.Text.Trim()+"'restoredatabasedb_CSManagefromdisk='"+textPaht.Text.Trim()+"'";SqlCommandsqlCmd=newSqlCommand(sql,sqlcon);sqlCmd.ExecuteNonQuery();sqlCmd.Dispose();sqlcon.Close();sqlcon.Dispose();MessageBox.Show("数据还原成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);MessageBox.Show("为了必免数据丢失,在数据库还原后将关闭整个系统。");Application.Exit();}else{MessageBox.Show("请选择备份文件!","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);}

附上整个进销存系统的源码 08.rar(5.8 MB)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。