QT中简单使用SQLITE数据库

来源:互联网 发布:mac游戏下载 编辑:程序博客网 时间:2024/05/01 08:25
QT中简单使用SQLITE数据库

代码:mian.cpp

 

[cpp] view plaincopyprint?
  1. #include <QtCore/QCoreApplication>  
  2. #include <QtSql>  
  3. #include <QDebug>  
  4. int main(int argc, char *argv[])  
  5. {  
  6.     QCoreApplication a(argc, argv);  
  7.     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");  
  8.     db.setDatabaseName("/tmp/my.db");  
  9.     if (!db.open())  
  10.     {  
  11.         qDebug()<<"open database failed ---"<<db.lastError().text()<<"/n";  
  12.         return -1;  
  13.     }  
  14.     QSqlQuery query;  
  15.     bool ok = query.exec("CREATE TABLE IF NOT EXISTS  people (id INTEGER PRIMARY KEY AUTOINCREMENT,"  
  16.                                        "name VARCHAR(20) NOT NULL,"  
  17.                                        "age INTEGER NULL)");  
  18.     if (ok)  
  19.     {  
  20.         qDebug()<<"ceate table partition success/n";  
  21.     }  
  22.     else  
  23.     {  
  24.         qDebug()<<"ceate table partition failed/n";  
  25.     }  
  26.     for (int i = 0; i< 3; ++i)  
  27.     {  
  28.         query.prepare("INSERT INTO people (id, name, age) VALUES (:id, :name, :age)");  
  29.         query.bindValue(":name", QString("smith_%1").arg(i+1));  
  30.         query.bindValue(":age", 20+i*5);  
  31.         query.exec();  
  32.     }  
  33.   
  34. //    QSqlQuery query;  
  35.     query.exec("SELECT id, name, age FROM people");  
  36.     while (query.next())  
  37.     {  
  38.         qDebug()<<"people("<<query.value(0).toInt()<<")  name:"<<query.value(1).toString()<<"  age:"<<query.value(2).toInt();  
  39.     }  
  40.     return a.exec();  
  41. }  

 

sql.pro:

[cpp] view plaincopyprint?
  1. QT       += core sql  
  2. QT       -= gui  
  3. TARGET = sql  
  4. CONFIG   += console  
  5. CONFIG   -= app_bundle  
  6. LIBS += -lsqlite3  
  7. TEMPLATE = app  
  8.   
  9. 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

 

0 0
原创粉丝点击