詳解Qt 連接SQLite操作
Qt 連接SQLite操作是本文要介紹的內(nèi)容,本文主要是介紹往數(shù)據(jù)庫中添加數(shù)據(jù)的插入操作,首先下載SQLite數(shù)據(jù)庫
首先到SQLite官方網(wǎng)站下載:
http://www.sqlite.org/download.html
得到sqlite3.exe。即可.就可以操作數(shù)據(jù)庫了。
運行cmd到該指定的目錄下,使用如下命令:如
F:\軟件\學(xué)習(xí)軟件\數(shù)據(jù)庫\SQlite\sqlite-3_6_17>sqlite3.exe test
并有以下提示:Enter SQL statements terminated with a ";"
就可以創(chuàng)建一個名為test的數(shù)據(jù)庫了.你可以使用.help命令查看各命令.
.databases 可以得到所有的數(shù)據(jù)庫。
可以使用如下命令得到一張表,并插入數(shù)據(jù)。***.quit退出.
F:\軟件\學(xué)習(xí)軟件\數(shù)據(jù)庫\SQlite\sqlite-3_6_17> create table student(id varchar(10),name varchar(20),age smallint);
F:\軟件\學(xué)習(xí)軟件\數(shù)據(jù)庫\SQlite\sqlite-3_6_17> select * from student;
F:\軟件\學(xué)習(xí)軟件\數(shù)據(jù)庫\SQlite\sqlite-3_6_17> insert into student values('1001' , 'lovesizhao' ,26);
F:\軟件\學(xué)習(xí)軟件\數(shù)據(jù)庫\SQlite\sqlite-3_6_17> select * from student;
- 1001|lovesizhao|26
F:\軟件\學(xué)習(xí)軟件\數(shù)據(jù)庫\SQlite\sqlite-3_6_17> drop table student;
F:\軟件\學(xué)習(xí)軟件\數(shù)據(jù)庫\SQlite\sqlite-3_6_17> .quit
而drop table student; 可以刪除該表格.其實大部操作都屬于SQL的相同沒什么改變.
也可以將該數(shù)據(jù)庫備份至output.sql,也稱為重定向
- sqlite3.exe test.db3 >output.sql
***可以將數(shù)據(jù)庫保存為test.db3即可。
下面講解如何通過Qt來訪問剛才建立的數(shù)據(jù)庫:
- QSqlDatabase dbconn = QSqlDatabase::addDatabase("QSQLITE", "testSQLite");
- dbconn.setDatabaseName("test.db3"); //當(dāng)前目錄下的test.db3數(shù)據(jù)庫文件
- //SQLite數(shù)據(jù)庫文件可用SQLite的命令行工具(c:\sqlite3.exe 數(shù)據(jù)庫名)或用SQLite GUI工具創(chuàng)建,SQLiteSpy
- if(!dbconn.open())
- {
- return;
- }
- QTableView *view;
- QSqlTableModel *model;
- view = new QTableView();
- model = new QSqlTableModel(this,dbconn);
- model->setTable("test");
- model->select();
- view->setModel(model);
也可以直接訪問內(nèi)存得到:如
- QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
- db.setDatabaseName(":memory:");
- if (!db.open()) {
- QMessageBox::critical(0, qApp->tr("Cannot open database"),
- qApp->tr("Unable to establish a database connection.\n"
- "This example needs SQLite support. Please read "
- "the Qt SQL driver documentation for information how "
- "to build it.\n\n"
- "Click Cancel to exit."), QMessageBox::Cancel);
- return false;
- }
- QSqlQuery query;
- query.exec("create table person (id int primary key, "
- "firstname varchar(20), lastname varchar(20))");
- query.exec("insert into person values(101, 'Danny', 'Young')");
- query.exec("insert into person values(102, 'Christine', 'Holand')");
- query.exec("create table images (locationid int, file varchar(20))");
- query.exec("insert into images values(0, 'images/oslo.png')");
- query.exec("insert into images values(1, 'images/brisbane.png')");
以下的操作只是往數(shù)據(jù)庫中添加數(shù)據(jù)的插入操作.如果想進(jìn)一步學(xué)習(xí),請查找相當(dāng)資料。
小結(jié):關(guān)于詳解Qt 連接SQLite操作的內(nèi)容介紹完了,希望本文對你有所幫助!更多關(guān)于數(shù)據(jù)庫的內(nèi)容請參考編輯推薦。