Qt operation database (access as an example)

Preliminary preparations:

Add QT + = sql in the .pro file (if it is vs + Qt joint programming, you need to check SQL when creating the project, or set it in the Qt Project Settings after creation) to
introduce the header files: #include <QSqlDatabase> and #include <QSqlQuery>

Connect to the access database:

SqlDatabase db;
db = QSqlDatabase::addDatabase("QODBC");
QString dbname = "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};FIL={MS Access};DBQ=" QCoreApplication::applicationDirPath() + "//test.mdb";
db.setDatabaseName(dbname);

Basic operation:

Add: (Two methods are applicable to other operations)

QSqlQuery query;
QString  sqlstr = "insert into point values(?,?,?)";//?是占位符query.prepare(sqlstr);
query.bindValue(0, x);
query.bindValue(1, y);
query.bindValue(2, z)query.exec();//prepare用于准备含?的语句,exec用于执行
          或者 
QSqlQuery query;
QString  sqlstr = "insert into point values(1,2,3)"; 
query.exec(sqlstr);

delete:

QSqlQuery query;
QString  sqlstr = " delete from point where x=1";
query.exec(sqlstr);

change:

QSqlQuery query;
QString  sqlstr = " update point set z=2,y=2 where x=1";
query.exec(sqlstr);

check:

QSqlQuery query;
QString  sqlstr = " select * from point where x>10";
query.exec(sqlstr);

Traverse the contents of the database:

First of all, we must add some header files: #include <QTextStream>, #include <QStringList>, #include <QSqlIndex>, #include <QSqlRecord>, #include <QtDebug>, #include <QSqlError> The
specific code is as follows:

    QString out_str;
    QTextStream out(stdout);
    QSqlError err;
    QSqlRecord record;

    if (db.open()) {
        qDebug() << "link successful!";
        //读数据库中的表
        QStringList tables;//所有的表名
        QString tabName,sqlString;
        tables = db.tables(QSql::Tables);
        //读表中记录
        for (int i = 0; i < tables.size(); ++i){
            tabName = tables.at(i);
            qDebug()<<tabName;
            sqlString = "select * from " + tabName;//sql语句
            QSqlQuery q;
            q.exec(sqlString);
            QSqlRecord rec = q.record();//视图中所包含的所有记录
            int fieldCount = rec.count();//字段的数量
            qDebug() << "Number of columns: " << fieldCount;//每条记录所含的字段

            QString fieldName;//字段的名称
            for(int i=0;i<fieldCount;i++){
                fieldName = rec.fieldName(i);
                out<<fieldName<<"\t";
            }
            out<<endl;
            while(q.next()){
                for(int i=0;i<fieldCount;i++){
                    out<<q.value(i).toString();
                    out<<"\t";
                }
                out<<endl;
            }
        }
Published 22 original articles · Likes2 · Visits 1157

Guess you like

Origin blog.csdn.net/qinqinxiansheng/article/details/105129610