日期:2014-05-16  浏览次数:20445 次

如何在Asp.net中备份Access数据库?

摘自:http://lovercoca.blog.163.com/blog/static/7098670220105825450787/

public   void   Create(   string   mdbPath   )
{
if(   File.Exists(mdbPath)   )   //检查数据库是否已存在
{
throw   new   Exception( "目标数据库已存在,无法创建 ");
}
//   可以加上密码,这样创建后的数据库必须输入密码后才能打开
mdbPath   =   "Provider=Microsoft.Jet.OLEDB.4.0;Data   Source= "   +   mdbPath;
//   创建一个CatalogClass对象的实例,
ADOX.CatalogClass   cat   =   new   ADOX.CatalogClass();
//   使用CatalogClass对象的Create方法创建ACCESS数据库
cat.Create(mdbPath);
}


///压缩修复ACCESS数据库,mdbPath为数据库绝对路径
public   void   Compact(   string   mdbPath   )
{
if(   !File.Exists(mdbPath)   )   //检查数据库是否已存在
{
throw   new   Exception( "目标数据库不存在,无法压缩 ");
}
//声明临时数据库的名称
string   temp   =   DateTime.Now.Year.ToString();
temp   +=   DateTime.Now.Month.ToString();
temp   +=   DateTime.Now.Day.ToString();
temp   +=   DateTime.Now.Hour.ToString();
temp   +=   DateTime.Now.Minute.ToString();
temp   +=   DateTime.Now.Second.ToString()   +   ".bak ";
temp   =   mdbPath.Substring(0,   mdbPath.LastIndexOf( "\\ ")+1)   +   temp;
//定义临时数据库的连接字符串
string   temp2   =   "Provider=Microsoft.Jet.OLEDB.4.0;Data   Source= "   +   temp;
//定义目标数据库的连接字符串
string   mdbPath2   =   "Provider=Microsoft.Jet.OLEDB.4.0;Data   Source= "   +   mdbPath;
//创建一个JetEngineClass对象的实例
JRO.JetEngineClass   jt   =   new   JRO.JetEngineClass();
//使用JetEngineClass对象的CompactDatabase方法压缩修复数据库
jt.CompactDatabase(   mdbPath2,   temp2   );
//拷贝临时数据库到目标数据库(覆盖)
File.Copy(   temp,   mdbPath,   true   );
//最后删除临时数据库
File.Delete(   temp   );  
}

///   备份数据库,mdb1,源数据库绝对路径;   mdb2:   目标数据库绝对路径  
public   void   Backup(   string   mdb1,   string   mdb2   )
{
if(   !File.Exists(mdb1)   )
{
throw   new   Exception( "源数据库不存在 ");
}
try
{
File.Copy(   mdb1,   mdb2,   true   );
}
catch(   IOException   ixp   )
{
throw   new   Exception(ixp.ToString());
}
}

///恢复数据库,mdb1为备份数据库绝对路径,mdb2为当前数据库绝对路径
public   void   Recover(   string   mdb1,   string   mdb2   )
{
if(   !File.Exists(mdb1)   )  
{
throw   new   Exception( "备份数据库不存在 ");  
}
try
{
File.Copy(   mdb1,   mdb2,   true   );
}
catch(   IOException   ixp   )
{
throw   new   Exception(ixp.ToString());
}
}

============================================================================================================

使用ADOX