WinForm c# 备份 还原 数据库, 其实是个非常简单的问题,一个Form,一个Button,一个OpenFileDialog,一个SaveFileDialog下面给出备份与还原类
using System;
using SystemCollectionsGeneric;
using SystemText;
using SystemData;
using SystemDataSqlClient;
using SystemIO;
using SystemCollections;
using SystemWindowsForms;
namespace 我的备份与还原
{
class 备份与还原数据库
{
static string connectionString = "server=;database=master;uid=sa;pwd=";
SqlConnection conn = new SqlConnection(connectionString);
/// <summary>
/// 备份指定的数据库文件
/// </summary>
/// <param name="databasename">要还原的数据库</param>
/// <returns></returns>
public bool BackUpDataBase( string databasefile)
{
if (!FileExists(databasefile))
{
}
//还原的数据库MyDataBase
string sql = "BACKUP DATABASE " + "MyDataBase" + " TO DISK = '" + databasefile + "bak' ";
connOpen();
SqlCommand comm = new SqlCommand(sql, conn);
commCommandType = CommandTypeText;
try
{
commExecuteNonQuery();
}
catch (Exception err)
{
string str = errMessage;
connClose();
return false;
}
connClose();//关闭数据库连接
return true;
}
//以下是还原数据库,稍微麻烦些,要关闭所有与当前数据库相连的连接
//------------------------------------------------------------------------------------------
public string RestoreDatabase(string backfile)
{
///杀死原来所有的数据库连接进程
SqlConnection conn = new SqlConnection();
connConnectionString = "Data Source=;Initial Catalog=master;User ID=sa;pwd =";
connOpen();
string sql = "SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocessesdbid=sysdatabasesdbid AND sysdatabasesName='" +
"MyDataBase"+ "'";
SqlCommand cmd1 = new SqlCommand(sql, conn);
SqlDataReader dr;
ArrayList list = new ArrayList();
try
{
dr = cmd1ExecuteReader();
while (drRead())
{
listAdd(drGetInt16(0));
}
drClose();
}
catch (SqlException eee)
{
MessageBoxShow(eeeToString());
}
finally
{
connClose();
}
for (int i = 0; i < listCount; i++)
{
connOpen();
cmd1 = new SqlCommand(stringFormat("KILL {0}", list[i]ToString()), conn);
cmd1ExecuteNonQuery();
connClose();
MessageBoxShow("系统已经清除的数据库线程: " + list[i]ToString() + "\r\n正在还原数据库!");
}
//这里一定要是master数据库,而不能是要还原的数据库,因为这样便变成了有其它进程
//占用了数据库。
string constr = @"Data Source=;Initial Catalog=master;User ID=sa;pwd =";
string database = MyDataBase;
string path = backfile;
string BACKUP = StringFormat("RESTORE DATABASE {0} FROM DISK = '{1}'", database, path);
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(BACKUP, con);
conOpen();
try
{
cmdExecuteNonQuery();
MessageBoxShow("还原成功,点击退出系统!");
ApplicationExit();
}
catch (SqlException ee)
{
//throw(ee);
//MessageBoxShow("还原失败");
MessageBoxShow(eeToString());
}
finally
{
conClose();
}
return "成功与否字符串";
}
}
}
以上就是关于通过c# winform程序如何对数据库进行备份和还原全部的内容,包括:通过c# winform程序如何对数据库进行备份和还原、、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)