Windows下qt使用sqlite

sqlitedemo.pro

QT += core sql
QT -= gui

CONFIG += c++11

TARGET = sqlitedemo
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

main.c

#include <QtCore/QCoreApplication>
#include <QtSql>
#include <QDebug>
#include <QSqlDatabase>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QSqlDatabase db;
    QDir dir(QDir::currentPath()+"/temp");
    if(!dir.exists()){
        dir.mkdir(QDir::currentPath()+"/temp");
    }
    bool isExist = QFile::exists(QDir::currentPath()+"/temp/my.db");
    if(!isExist){
        db = QSqlDatabase::addDatabase("QSQLITE","my");
    }else{
        db = QSqlDatabase::addDatabase("QSQLITE");
    }
    db.setDatabaseName(QDir::currentPath()+"/temp/my.db");
    if (!db.open())
    {
        qDebug()<<"open database failed ---"<<db.lastError().text()<<"/n";
        return -1;
    }
    QSqlQuery query(db);
    bool ok = query.exec("CREATE TABLE IF NOT EXISTS  people (id INTEGER PRIMARY KEY AUTOINCREMENT,"
                                       "name VARCHAR(20) NOT NULL,"
                                       "age INTEGER NULL)");
    if (ok)
    {
        qDebug()<<"ceate table partition success/n";
    }
    else
    {
        qDebug()<<"ceate table partition failed/n";
    }
    for (int i = 0; i< 3; ++i)
    {
        query.prepare("INSERT INTO people (id, name, age) VALUES (:id, :name, :age)");
        query.bindValue(":name", QString("smith_%1").arg(i+1));
        query.bindValue(":age", 20+i*5);
        query.exec();
    }
    query.exec("SELECT id, name, age FROM people");
    while (query.next())
    {
        qDebug()<<"people("<<query.value(0).toInt()<<")  name:"<<query.value(1).toString()<<"  age:"<<query.value(2).toInt();
    }
    return a.exec();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值