關于QT中SQLite數(shù)據(jù)庫編程
QT中SQLite數(shù)據(jù)庫編程是本文要介紹的內(nèi)容,主要是來學習QT中數(shù)據(jù)庫的操作,具體內(nèi)容來看詳細內(nèi)容講解。QT支持輕量級數(shù)據(jù)庫SQLite,接下來測試這個數(shù)據(jù)庫的基本操作
環(huán)境:Ubuntu10.04 + Qt4.7.0
要支持數(shù)據(jù)庫編程,首先在工程文件中增加:
- QT += sql
- 頭文件:#include <QtSql>
下面新建一個數(shù)據(jù)庫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;
- }
注意:如果數(shù)據(jù)庫名稱為:memory:,則只在內(nèi)存中建立表.
此程序移植到嵌入式linux中一樣可以運行。
小結:關于QT中SQLite數(shù)據(jù)庫編程的內(nèi)容介紹完了,希望通過本文的學習能對你有所幫助!