#ifndef ACCESSDB_H #define ACCESSDB_H #include <QtSql> #include <QDomDocument> class AccessDB { public: AccessDB(unsigned int max = 100000); AccessDB(QString path,QString list,QString pwd = "123456",unsigned int max = 100000); ~AccessDB(); public: void SetMax(const unsigned int m); unsigned int GetMax(); void SetDBPath(const QString& path); void SetDBList(const QString& list); void SetDBPassword(const QString& pwd); //QString GetCurrentID(); public: bool isExist(const QString &filePath); bool isFull(); bool Open(const QString& connectName); bool Open(const QString& path,const QString &connectName); bool Query(const QString& sql); bool Close(); //bool Close(const QString& connectName); bool CreateDB(const QString &filePath,const QString &lName); void WriteDBInfo(); void GetDBInfo(const QString func,QDomElement dbNode); QStringList GetDBList(const QString& rootPath); public: QString errorString; QSqlQuery mQuery; private: unsigned int m_Max; QString dbPath; QString dbList; QString password; QString connID; QSqlDatabase mConnect; QDomDocument doc; }; #endif // ACCESSDB_H
#include "AccessDB.h" #include <QMessageBox> #include <windows.h> #include "ODBCINST.H" AccessDB::AccessDB(unsigned int max) :m_Max(max) { } AccessDB::AccessDB(QString path,QString list,QString pwd,unsigned int max) :dbPath(path),dbList(list),password(pwd),m_Max(max) { } AccessDB::~AccessDB() { } //设置数据库上限 void AccessDB::SetMax(const unsigned int m) { m_Max = m; } //获取数据库上限 unsigned int AccessDB::GetMax() { return m_Max; } void AccessDB::SetDBPath(const QString& path) { dbPath = path; } void AccessDB::SetDBList(const QString& list) { dbList = list; } void AccessDB::SetDBPassword(const QString& pwd) { password = pwd; } //***************************************************************************** //判断数据库是否存在 bool AccessDB::isExist(const QString &filePath) { QFile file(filePath); return file.exists(); } //判断数据库是否满(默认100000,m_Max的值) /* * 请先设置好表名SetDBList(const QString& list); */ bool AccessDB::isFull() { bool ret = Query("SELECT COUNT(*) FROM "+ dbList +";"); if(mQuery.next()) { int count = mQuery.value(0).toInt(); qDebug()<< "count:"<<count<<"m_Max:"<<m_Max; if(count >= m_Max) { return true; } else { return false; } } } QStringList AccessDB::GetDBList(const QString& rootPath) { QStringList mfilesList; QStringList filterList; filterList.append("*.mdb"); QDir dir = QDir(rootPath); Q_ASSERT(dir.exists()); foreach(QString fileName,dir.entryList(filterList,QDir::Files,QDir::Time)) { mfilesList.append(rootPath+"\\"+fileName); } return mfilesList; } //******************************************************************************* /*注意: * 1.mConnect 由 connID唯一命名 * 2.使用Close 只是断开与db的链接 */ bool AccessDB::Open(const QString& connectName) { connID = dbPath + "-" + connectName; mConnect = QSqlDatabase::database(connID,false); if(!mConnect.isValid()) { mConnect = QSqlDatabase::addDatabase("QODBC",connID); QString dsn = QString("DRIVER={Microsoft Access Driver (*.mdb)};FIL={Meteorology Access};DBQ=%1;UID=;PWD=%2") .arg(dbPath).arg(password); //qDebug()<<"creatConnect"<<dbName<<listName; mConnect.setDatabaseName(dsn); }//如果以connID标识的 驱动存在,则不在设置mConnect的DSN; if(!mConnect.isOpen()) { if(!mConnect.open()) { errorString = "Open database error:"+mConnect.lastError().text(); return false; } } qDebug()<<"Open Access ID:"<<connID; return true; } bool AccessDB::Open(const QString& path,const QString &connectName) { dbPath = path; connID = dbPath + "-" + connectName; mConnect = QSqlDatabase::database(connID,false); if(!mConnect.isValid()) { mConnect = QSqlDatabase::addDatabase("QODBC",connID); QString dsn = QString("DRIVER={Microsoft Access Driver (*.mdb)};FIL={Meteorology Access};DBQ=%1;UID=;PWD=%2") .arg(dbPath).arg(password); //qDebug()<<"creatConnect"<<dbName<<listName; mConnect.setDatabaseName(dsn); } if(!mConnect.isOpen()) { if(!mConnect.open()) { errorString = "Open database error:"+mConnect.lastError().text(); return false; } } qDebug()<<"Open Access ID:"<<connID; return true; } //******************************************************************************* bool AccessDB::Close() { mQuery.clear(); mConnect.close(); qDebug()<<"Close Access ID:"<<connID; } bool AccessDB::Query(const QString& sql) { mQuery = QSqlQuery(mConnect); if(mQuery.prepare(sql)) { return mQuery.exec(); } else { errorString = "Query prepare failed!"; qDebug()<<errorString; return false; } } //创建数据库 bool AccessDB::CreateDB(const QString &filePath,const QString &lName) { typedef BOOL(*SQLConfigDataSourceFunc)(HWND,WORD,LPCSTR,LPCSTR); SQLConfigDataSourceFunc SQLConfigDataSource = NULL; QLibrary dllLib("odbccp32.dll"); if(!dllLib.load()) { errorString = "load <odbccp32.dll> failed!"; return false; } else { SQLConfigDataSource = (SQLConfigDataSourceFunc)dllLib.resolve("SQLConfigDataSource"); if(SQLConfigDataSource == NULL) { errorString = "Resolve SQLConfigDataSource failed!"; dllLib.unload(); return false; } else { QString lpszAttributes = "CREATE_DB="+filePath + " General"; //QString lpszAttributes = "CREATE_DB=.\\" + dbName + ".mdb General"; BOOL fCreated; fCreated = SQLConfigDataSource(NULL, ODBC_ADD_DSN, "Microsoft Access Driver (*.mdb)", lpszAttributes.toStdString().c_str()); //"CREATE_DB=.\\ATest.mdb General\0" ); if(!fCreated) { errorString = "Create Access file failed!"; return false; } dbPath = filePath; dbList = lName; if(!Open("create")) { errorString = "Open Access failed!"; dllLib.unload(); return false; } bool queryRet = Query("CREATE TABLE " + lName + "(ID Counter primary key,DT DateTime,SEC Long,WD Text(255),SD Text(255),QY Text(255),XDFX Text(255),XDFS Text(255),ZFX Text(255),ZFS Text(255),FJ Text(255),CWJD Text(255),CWWD Text(255),XDHX Text(255),DDHS Text(255));"); //Query("INSERT INTO " + lName + "(D)values('2015-04-10 09:47:10');"); if(!queryRet) { errorString = "Open create table failed!"; dllLib.unload(); return false; } Close(); dllLib.unload(); SetDBList(lName); return true; } } } //获取数据库的信息(以写Config文件用) void AccessDB::GetDBInfo(const QString func,QDomElement dbNode) { QDomElement childNode = doc.createElement(func); //QString queryStr = "SELECT max(ID),max(SEC),max(WD),max(SD),max(QY),max(XDFX),max(XDFS),max(ZFX),max(ZFS),max(FJ),max(CWJD),max(CWWD),max(XDHX),max(DT) as maxvalue FROM " + listName +";"; QString queryStr = "SELECT "+ func +"(ID)," + func + "(DT),"+ func +"(SEC)," + func +"(WD),"+func +"(SD)," + func +"(QY)," + func +"(XDFX),"+func +"(XDFS)," + func +"(ZFX)," + func +"(ZFS),"+ func +"(FJ)," + func +"(CWJD)," + func +"(CWWD),"+ func +"(XDHX) as maxvalue FROM " + dbList +";"; Query(queryStr); if(mQuery.next()) { childNode.setAttribute("ID",mQuery.value(0).toString()); childNode.setAttribute("DT",mQuery.value(1).toString()); childNode.setAttribute("SEC",mQuery.value(2).toString()); childNode.setAttribute("WD",mQuery.value(3).toString()); childNode.setAttribute("SD",mQuery.value(4).toString()); childNode.setAttribute("QY",mQuery.value(5).toString()); childNode.setAttribute("XDFX",mQuery.value(6).toString()); childNode.setAttribute("XDFS",mQuery.value(7).toString()); childNode.setAttribute("ZFX",mQuery.value(8).toString()); childNode.setAttribute("ZFS",mQuery.value(9).toString()); childNode.setAttribute("FJ",mQuery.value(10).toString()); childNode.setAttribute("CWJD",mQuery.value(11).toString()); childNode.setAttribute("CWWD",mQuery.value(12).toString()); childNode.setAttribute("XDHX",mQuery.value(13).toString()); } dbNode.appendChild(childNode); } //********************************************************* //Config 文件格式 /*<Config> <DB name="DB201504130832" num="100000"> <Min dt="" wd="40" sd="30"/> <Max dt="" wd="40" sd="30"/> <Avg wd="" sd=""/> </DB> <DB name="DB201504140839" num="100000"> <Min dt="" wd="40" sd="30"/> <Max dt="" wd="40" sd="30"/> <Avg wd="" sd=""/> </DB> </Config>*/ //************************************************************ void AccessDB::WriteDBInfo() { //求filePath的各属性的峰值、均值 QFile file(".\\Access\\Config.xml"); QDomDocument doc; if(file.open(QFile::ReadWrite|QFile::Text)) { //QXmlStreamWriter xmlWriter(&file); //xmlWriter. if (!doc.setContent(&file)) { file.close(); return; } QDomElement rootElem = doc.documentElement(); QDomElement dbNode = doc.createElement("DB"); dbNode.setAttribute("Path",dbPath); //note.setAttribute("num","100000"); GetDBInfo("min",dbNode); GetDBInfo("max",dbNode); GetDBInfo("avg",dbNode); rootElem.appendChild(dbNode); file.close(); } QFile file2(".\\Access\\Config.xml"); if(!file2.open(QIODevice::WriteOnly|QIODevice::Truncate|QIODevice::Text)) return; QTextStream out(&file2); out.setCodec("UTF-8"); doc.save(out,4,QDomNode::EncodingFromTextStream); file2.close(); }