代码:mian.cpp

 

#include <QtCore/QCoreApplication> 
#include <QtSql> 
#include <QDebug> 
int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");    
    db.setDatabaseName("/tmp/my.db"); 
    if (!db.open()) { 
        qDebug()<<"open database failed ---"<<db.lastError().text()<<"\n"; 
        return -1; 
    } 
    QSqlQuery query; 
    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 successn"; 
    } else { 
        qDebug()<<"ceate table partition failed"; 
    } 
    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(); 
    } 
    // QSqlQuery query; 
    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(); 
}

 

sql.pro:

QT += core sql QT -= gui TARGET = sql CONFIG += console CONFIG -= app_bundle LIBS += -lsqlite3 TEMPLATE = app SOURCES += main.cpp

 

编译运行,输出:

ceate table partition success

 

people( 1 ) name: "smith_1" age: 20

people( 2 ) name: "smith_2" age: 25

people( 3 ) name: "smith_3" age: 30

 

Logo

助力广东及东莞地区开发者,代码托管、在线学习与竞赛、技术交流与分享、资源共享、职业发展,成为松山湖开发者首选的工作与学习平台

更多推荐