Qt中SQLite数据库编程
1、要支持数据库编程,首先在工程文件中增加:
QT += sql 头文件:#include <QtSql>
2、下面新建一个数据库test,然后新建一个表test_table,在表中新建两个字段:id,name。然后查询表,并显示。
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); //db.setHostName("fedora12"); db.setDatabaseName("test"); //db.setUserName("jdh"); //db.setPassword("123456"); if (!db.open()) { cout << "shu ju ku dabukai!!!!!!!" << endl; } cout << "shu ju ku cao zuo---------------!!!!!!!" << endl; QSqlQuery q; if (q.exec("CREATE TABLE test_table (id INT PRIMARY KEY,name VARCHAR)") == false) { cout << "shu ju ku dabukai22222222!!!!!!!" << endl; } q.exec("insert into test_table values (8,'LiLei')"); q.exec("insert into test_table values (46,'HanMeiMei')"); q.exec("select * from test_table"); while (q.next()) { cout << "caozuo!!" << endl; int id = q.value(0).toInt(); QString name = q.value(1).toString(); qDebug() << id << name << endl; } QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); //db.setHostName("fedora12"); db.setDatabaseName("test"); //db.setUserName("jdh"); //db.setPassword("123456"); if (!db.open()) { cout << "shu ju ku dabukai!!!!!!!" << endl; } cout << "shu ju ku cao zuo---------------!!!!!!!" << endl; QSqlQuery q; if (q.exec("CREATE TABLE test_table (id INT PRIMARY KEY,name VARCHAR)") == false) { cout << "shu ju ku dabukai22222222!!!!!!!" << endl; } q.exec("insert into test_table values (8,'LiLei')"); q.exec("insert into test_table values (46,'HanMeiMei')"); q.exec("select * from test_table"); while (q.next()) { cout << "caozuo!!" << endl; int id = q.value(0).toInt(); QString name = q.value(1).toString(); qDebug() << id << name << endl; }
如果数据库名称为:memory:,则只在内存中建立表.