---
title: "Qt+SQLite3"
author: "summerbell"
date: "2011-08-24T14:34:18Z"
tags: []
categories: ["数据库"]
slug: "qt-sqlite3"
draft: false
lastmod: "2011-08-27T23:19:58Z"
id: 1156849
url: "https://summerbell.iteye.com/blog/1156849"
---

SQLite是遵守ACID的关联式数据库管理系统，它包含在一个相对小的C库中。

**另外别忘记在.pro文件中添加 QT  += sql**  
**在程序中#include &lt;QtSQL&gt;**

 

```
#include <QtCore/QCoreApplication>
#include <QtSql>
#include <QtDebug>


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

    QCoreApplication a(argc, argv);

    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8"));


    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName("/home/summerbell/msg2.db"); // 数据库名与路径, 此时是放在同目录下

    db.open(); // 连接数据库, 然后就可以使用了.


    QSqlQuery query;

    //    query.prepare("insert into user(id, name) values(:id, :name)");

    //    query.bindValue(":id", 2);

    //    query.bindValue(":name", "黄彪");

    //    bool ok = query.exec();

    //

    //    query.prepare("insert into user(id, name) values(:id, :name)");

    //    query.bindValue(":id", 3);

    //    query.bindValue(":name", "阿跑");

    //    query.exec();

    //

    //    if (!ok) {

    //        qDebug() << "Already exits.";

    //    }

    //

    //    query.exec("create table hello(id int primary key)");


    query.exec("select * from msgs");

    while (query.next()) {
         qDebug() << "3";



        QString time = query.value(0).toString();
        int read = query.value(1).toInt();
        QString content = query.value(2).toString();
        qDebug() << "time=" << time << ", read=" << read << ", content=" << content;

    }

    qDebug() << "4";
    db.close();
    return 0;

}
```