#include "stdafx.h"
#include <iostream>
#include "stdio.h"
#include <direct.h>
#include <io.h>
using namespace std;
/*
Filepath :数据库文件路径,不包括文件名例如:Filepath="..\\"
SrcFileName :源文件名
*/
static bool compressMDB(const std::string& Filepath,const std::string &SrcFileName)
{
string backupfilepath;//备份文件夹路径
backupfilepath=Filepath;
backupfilepath+="BackUp";
string srcpath=Filepath;//源文件路径,包括源文件
srcpath+=SrcFileName;
string backup=backupfilepath;//源文件备份路径,包括源文件
backup+="\\";
backup+=SrcFileName;
#if 0
if(CopyFile(backup.c_str(),srcpath.c_str(),FALSE))
{
cout<<"还原成功"<<endl;
}
else
{
cout<<"还原失败"<<endl;
}
#endif
#if 1
/*判断BackUp文件夹是否存在,不存在创建文件夹,存在清空文件夹*/
if(!access(backupfilepath.c_str(),0))
{
/*存在,清空文件夹*/
string DelFile=backupfilepath;
DelFile+="\\";
DelFile+=SrcFileName;
remove(DelFile.c_str());
}
else
{
/*不存在*/
mkdir(backupfilepath.c_str());
}
/*备份源文件*/
if(CopyFile(srcpath.c_str(),backup.c_str(),FALSE))
{
cout<<"备份成功"<<endl;
}
else
{
cout<<"备份失败"<<endl;
}
/*删除原文件*/
if(!remove(srcpath.c_str()))
{
cout<<"删除原文件成功"<<endl;
}
CoInitialize(NULL);
try
{
string strSourceConnection;
strSourceConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
strSourceConnection += backup;
strSourceConnection += ";Jet OLEDB:Engine Type=5;";
string strDestConnection;
strDestConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
strDestConnection +=srcpath;
strDestConnection += ";Jet OLEDB:Engine Type=5;";
IJetEnginePtr jet(__uuidof(JetEngine));
jet->CompactDatabase(strSourceConnection.c_str(), strDestConnection.c_str());
}
catch(...)
{
if(CopyFile(backup.c_str(),srcpath.c_str(),FALSE))
{
cout<<"还原成功"<<endl;
}
else
{
cout<<"还原失败"<<endl;
}
CoUninitialize();
return false;
}
CoUninitialize();
#endif
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
string path="..\\DB\\";
string sz="Transaction.mdb";
if(compressMDB(path,sz))
{
cout<<"压缩成功"<<endl;
}
else
{
cout<<"压缩失败"<<endl;
}
getchar();
return 0;
}