#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;
}