转自:http://www.cppblog.com/biao/archive/2009/04/15/79958.html
#include <QtCore/QCoreApplication> #include <Qtsql> #include <qDebug> int main(int argc,char *argv[]) { QCoreApplication a(argc,argv); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8")); QsqlDatabase db = QsqlDatabase::addDatabase("QsqlITE"); db.setDatabaseName("MyDB"); // 数据库名与路径,此时是放在同目录下 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,3); // query.bindValue(":name","阿跑"); // query.exec(); // // if (!ok) { // qDebug() << "Already exits."; // } // // query.exec("create table hello(id int primary key)"); query.exec("select * from user"); while (query.next()) { int id = query.value(0).toInt(); QString name = query.value(1).toString(); qDebug() << "Id=" << id << ",Name=" << name; } return 0; }