关于QT和SQLite以及XML

就关于qt连接使用sqlite折腾了一晚上.倒也不全是因为数据库连接的问题, 主要还是数据格式各自出问题.

原来的数据库是access, 为了导入linux下的sqlite, 我把其输出格式改成了xml文档. 然后在qt中对其进行解析.

//    QDomElement docElem = doc.documentElement();
//    //QDomNode n = docElem.firstChild();
//    QDomNodeList list = doc.elementsByTagName(QString("Row")).at(0).toElement().childNodes();

//    QString s = "";
//    for(int i=0; i<list.length();i++){
//        s += list.at(i).toElement().text();
//        if(i!=list.length()-1){
//            s += ",";
//        }
//    }
//    qDebug()<<qPrintable(s);

以上获得的是表的字段, 通过获得的字符串我直接在命令行里创建了一个表.

然后就是数据的添加了.

首先新建一个connection.h头文件

#ifndef CONNECTION_H
#define CONNECTION_H
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>

static bool createConnection(){
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("/home/hao/Dangers/Danger.db");

    if(!db.open()){
        qDebug() <<"aaaa";
        QMessageBox::critical(0,"Cannot open database",
                              "unable to establish a database connection.", QMessageBox::Cancel);
        return false;
    }


    return true;
}

#endif // CONNECTION_H

 当然工程要加上   

QT       += core gui sql xml
然后就是在main.cpp进行操作了
#include<QApplication>
#include<QSqlDatabase>
#include<QDebug>
#include <QString>
#include<QStringList>
#include <QtCore/QCoreApplication>
#include <QtXml>
#include "connection.h"
#include <QVariant>

int main(int argc, char * argv[]){

    QApplication a(argc,argv);

    qDebug() << QDir::currentPath();
    QDomDocument doc;
    QFile file("../database/important.xml");
    if(!file.open(QIODevice::ReadOnly)) {
        qDebug() << "open failed";
        return 0;
    }
    if(!doc.setContent(&file)){
        file.close();
        return 0;
    }

    file.close();


    if(!createConnection()) {
        qDebug() <<"connection failed";
        return 1;
    }


    QSqlQuery query;

    QDomElement docElem = doc.documentElement();
    QDomNodeList list = doc.elementsByTagName(QString("Row"));

    for(int i=1; i<list.length(); i++){
        QString s = "";
        int index = 1;
        QDomNodeList attrs = list.at(i).childNodes();
        for(int j=0; j<attrs.length(); j++){
            if(attrs.at(j).toElement().attribute(QString("ss:Index"))!=""){    //这里处理费了一阵功夫,因为这个xml文档中,当有些字段为空时,它会直接加一个index的标示符,而之前的就不生成节点了.
                while(index < attrs.at(j).toElement().attribute(QString("ss:Index")).toInt()){
                    s = s+"\'" + "\'" + ",";
                    index ++;
                }

            }
            index ++;
            s += '\''+attrs.at(j).toElement().text()+'\'';
            if(index<=96){
                s += ',';
            }
        }
        while(index <= 96){    //一共有96个字段
            s = s+ "\'" + "\'";
            if(index !=96){
                s+=",";
            }
            index++;
        }
        QString sr = "insert into tablename values("+s+")";
        query.exec(sr+";");
        qDebug() << "--------------------------------";
        qDebug() << qPrintable(sr);

    }
    qDebug() << list.length();

    return a.exec();
}

 

/********2016.8.25更新********************/

研究了一上午, 写了一个连接数据库的模板类.

之后当然会有更多的扩充

/*******connectdb.h***********/
#ifndef CONNECTDB_H
#define CONNECTDB_H

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QString>
#include <QMessageBox>
#include <QComboBox>

class ConnectDB
{
public:
    ConnectDB(QString dbname="database.db
");
    //ConnectDB();
    ~ConnectDB();

    QSqlDatabase db;
    QSqlQuery select(QString sql);

    void getSubstance(QComboBox *box);
};

#endif // CONNECTDB_H



/****************connectdb.cpp*************/
#include "connectdb.h"
#include <QDebug>

ConnectDB::ConnectDB(QString dbname)
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbname);
    if( !db.open() ){
        QMessageBox::critical(0, "Cannot open database",
                              "Unable to establish a database connection.", QMessageBox::Cancel);
    }
}

ConnectDB::~ConnectDB(){

}

QSqlQuery ConnectDB::select(QString sql){
    QSqlQuery query;
    query.exec(sql);
    return query;
}

//这个函数作用是获取数据库中的物质名称填充到组件的comboBox中去
void ConnectDB::getSubstance(QComboBox *box){
   QString sql = "select 中文名称 from tablename order by id";
   QSqlQuery query = this->select(sql);
   while(query.next()){
       QString item = query.value(0).toString();
       box->addItem(QString(item));
   }
}



/**********调用方法************/


#include "connectdb.h"

......

ConnectDB *db = new ConnectDB();

    ComboBox *nameSelect = new QComboBox;
    db->getSubstance(nameSelect);
    

 

posted on 2016-08-25 00:04  杠子  阅读(1027)  评论(0编辑  收藏  举报

导航