Qt中SQLite3的增、刪、改、查操作

QT & sqlite3:

先說一下QT自帶數據庫sqlite3和另外用sqlite3插件的區別,他們的功能是一樣的,但是代碼就不一樣了。QT對數據庫具有完善的支持,不需要加任何其他插件就可以直接使用,但是如果你要是加了sqlite3插件,調用數據庫就跟直接調用一個驅動一樣,直接調用接口函數:openclose……,換言之QT自帶的數據庫語言就用不上了。

一、使用Qt自帶的數據庫sqlite3

Qt自帶了很多常用的數據庫驅動,使用起來非常方便如下圖所示:


使用Qt自帶數據庫SQLite3的代碼實例:

Connect to Sqlite and do insert, delete, update and select

  

Foundations of Qt Development\Chapter13\sqltest\sqlite\main.cpp
/*
 * Copyright (c) 2006-2007, Johan Thelin
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice, 
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,  
 *       this list of conditions and the following disclaimer in the documentation 
 *       and/or other materials provided with the distribution.
 *     * Neither the name of APress nor the names of its contributors 
 *       may be used to endorse or promote products derived from this software 
 *       without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <QApplication>

#include <QtSql>
#include <QtDebug>

int main( int argc, char **argv )
{
  QApplication app( argc, argv );
   //創建連接
  QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );//第二個參數可以設置連接名字,這裏爲default

  db.setDatabaseName( "./testdatabase.db" );// 設置數據庫名與路徑, 此時是放在上一個目錄
  //打開連接
  if( !db.open() )
  {
    qDebug() << db.lastError();
    qFatal( "Failed to connect." );
  }
    
  qDebug( "Connected!" );
  //各種操作
  QSqlQuery qry;
  //創建table
  qry.prepare( "CREATE TABLE IF NOT EXISTS names (id INTEGER UNIQUE PRIMARY KEY, firstname VARCHAR(30), lastname VARCHAR(30))" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug() << "Table created!";
    //增
  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (1, 'John', 'Doe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (2, 'Jane', 'Doe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (3, 'James', 'Doe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (4, 'Judy', 'Doe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (5, 'Richard', 'Roe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (6, 'Jane', 'Roe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (7, 'John', 'Noakes')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (8, 'Donna', 'Doe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );

  qry.prepare( "INSERT INTO names (id, firstname, lastname) VALUES (9, 'Ralph', 'Roe')" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Inserted!" );
//查詢
  qry.prepare( "SELECT * FROM names" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
  {
    qDebug( "Selected!" );
    
    QSqlRecord rec = qry.record();
    
    int cols = rec.count();
    
    for( int c=0; c<cols; c++ )
      qDebug() << QString( "Column %1: %2" ).arg( c ).arg( rec.fieldName(c) );
      
    for( int r=0; qry.next(); r++ )
      for( int c=0; c<cols; c++ )
        qDebug() << QString( "Row %1, %2: %3" ).arg( r ).arg( rec.fieldName(c) ).arg( qry.value(c).toString() );
  }
  
  
  qry.prepare( "SELECT firstname, lastname FROM names WHERE lastname = 'Roe'" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
  {
    qDebug( "Selected!" );
    
    QSqlRecord rec = qry.record();
    
    int cols = rec.count();
    
    for( int c=0; c<cols; c++ )
      qDebug() << QString( "Column %1: %2" ).arg( c ).arg( rec.fieldName(c) );
      
    for( int r=0; qry.next(); r++ )
      for( int c=0; c<cols; c++ )
        qDebug() << QString( "Row %1, %2: %3" ).arg( r ).arg( rec.fieldName(c) ).arg( qry.value(c).toString() );
  }


  qry.prepare( "SELECT firstname, lastname FROM names WHERE lastname = 'Roe' ORDER BY firstname" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
  {
    qDebug( "Selected!" );
    
    QSqlRecord rec = qry.record();
    
    int cols = rec.count();
    
    for( int c=0; c<cols; c++ )
      qDebug() << QString( "Column %1: %2" ).arg( c ).arg( rec.fieldName(c) );
      
    for( int r=0; qry.next(); r++ )
      for( int c=0; c<cols; c++ )
        qDebug() << QString( "Row %1, %2: %3" ).arg( r ).arg( rec.fieldName(c) ).arg( qry.value(c).toString() );
  }


  qry.prepare( "SELECT lastname, COUNT(*) as 'members' FROM names GROUP BY lastname ORDER BY lastname" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
  {
    qDebug( "Selected!" );
    
    QSqlRecord rec = qry.record();
    
    int cols = rec.count();
    
    for( int c=0; c<cols; c++ )
      qDebug() << QString( "Column %1: %2" ).arg( c ).arg( rec.fieldName(c) );
      
    for( int r=0; qry.next(); r++ )
      for( int c=0; c<cols; c++ )
        qDebug() << QString( "Row %1, %2: %3" ).arg( r ).arg( rec.fieldName(c) ).arg( qry.value(c).toString() );
  }
  //更新
  qry.prepare( "UPDATE names SET firstname = 'Nisse', lastname = 'Svensson' WHERE id = 7" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Updated!" );

  qry.prepare( "UPDATE names SET lastname = 'Johnson' WHERE firstname = 'Jane'" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Updated!" );
  //刪除
  qry.prepare( "DELETE FROM names WHERE id = 7" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Deleted!" );

  qry.prepare( "DELETE FROM names WHERE lastname = 'Johnson'" );
  if( !qry.exec() )
    qDebug() << qry.lastError();
  else
    qDebug( "Deleted!" );


  db.close();

  return 0;
}
二、Qt中使用sqlite3插件

1、安裝sqlite3插件

從官方網站http://www.sqlite.org下載完整版本。

2、安裝sqlite3

網上可以看到很多修改下載之後的源代碼的論壇,我估計那些帖子比較老一點,最新版的代碼已經不存在那些bug了,可以直接編譯

 *注意複製粘貼庫函數的時候有的動態鏈接庫如果單獨複製會丟失之間的鏈接關係,所以需要一塊複製

cp -arf libsqlite3.so libsqlite3.so.0 libsqlite3.so.0.8.6 。。。

3、移植sqlite3

QTEinclude文件中建立新文件夾sqlite3,將頭文件放到裏面;把庫文件放到QTElib文件中

4編程代碼實例:

1 QT生成的.pro文件中添加庫指令: LIBS += -lsqlite3

2 在調用數據庫的文件的頭文件裏添加頭文件和變量

 #include "sqlite3/sqlite3.h"            

 sqlite3 *db;        //數據庫

 char *zErrMsg;      //出錯信息

 char  **resultp;    //調用時的保存位置

 int  nrow;          //列數

int  ncolumn;       //行數

 char  *errmsg;      //出錯信息

3)新建或打開數據庫      

if( (sqlite3_open("people.db", &db)) != 0 ){

qDebug()<<"sqlite3 open is false";

 }

else {

qDebug()<<"sqlite3 open is OK";

 }

4 建立表格

sqlite3_exec(db, "create table person(name varchar(30) PRIMARY KEY, age int);", NULL, NULL, &zErrMsg);

*添加 PRIMARY KEY 是指定主鍵,每個數據庫只能有一個,主鍵的值不能重複,比方說你設定name爲主鍵,則相同名字的人只能保存第一個,其他的忽略不計。若想避免這種情況,則去掉主鍵或者設定id號爲主鍵(id號一直加一,不會重複)。

5)往表格裏寫入信息

 a.直接添加數據  

 sqlite3_exec(db, "insert into person values('張翼', 30)", NULL, NULL, &zErrMsg);

 sqlite3_exec(db, "insert into person values('hongdy', 28)", NULL, NULL, &zErrMsg);                     

 b.添加數字變量

 int  data=10;

 char sql2[100];  //必須寫明大小,劃分內存,如果只寫一個 char *sql2,會出現段錯誤

 sprintf(sql2,"insert into person values('張翼',%d);",data);

sqlite3_exec(db,sql2,NULL,NULL,&zErrMsg);

*sprintf的作用是字串格式化命令,主要功能是把格式化的數據寫入某個字符串中

 c.添加字符串變量

 char data[]="張翼";

 char sql2[100];

 sprintf(sql2,"insert into person values('%s',10);",data);

sqlite3_exec(db,sql2,NULL,NULL,&zErrMsg);

 * %s需要用單引號註釋             

d.添加text中的變量到數據庫中

 這裏需要漢字編碼的問題,Windows下默認GBKGB2312編碼,Linux下默認UTF-8編碼,所以如果沒有設置好會出現亂碼

d1. main.cpp中添加以下指令,支持中文顯示 

 #include <QTextCodec>

QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));

QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

d2. 讀取保存

 char *abc=ui->lineEdit->text().toUtf8().data();   //QString char*

 sprintf(sql2,"insert into person values('%s',%d);",abc,data);

sqlite3_exec(db,sql2,NULL,NULL,&zErrMsg);

*在調試的時候如果用串口超級終端調試的話,在ARM上顯示正常,但是在串口是亂碼,不要被迷惑

6)查詢、調用數據庫

a. 查詢全部

sqlite3_get_table(db, "select * from person", &resultp, &nrow, &ncolumn, &errmsg);

*resultp保存數據庫信息,nrow返回列數,ncolumn返回列數

b. 查詢部分信息

sqlite3_get_table(db, "select * from person where name='zhang'", &resultp, &nrow, &ncolumn, &errmsg);

c. 變量查詢查詢

 char data[]="張翼";

 char sql3[100];

 sprintf(sql3,"select * from person where name='zhang';",data);

 sqlite3_get_table(db, sql3, &resultp, &nrow, &ncolumn, &errmsg);

 *查詢時使用變量的方法和添加時一樣

(7)關閉數據庫

 sqlite3_close(db);

三、VS+QT使用SQL驅動

//1.添加SQL庫:"Qt project setting"-->"Qt Modules",在SQL library複選框前打勾.或者在vs項目屬性--》連接器--》輸入里加入Qt5Sqllib
//2.添加頭文件
//#include<QtSql>//這樣寫會報Cannot open include file: 'QtSql': No such file or directory,奇葩錯誤,因爲QtSql只是一個文件夾
#include <QtSql/QSqlDatabase>//這樣寫可以
#include <QtSql/QSqlTableModel>
#include<QtSql/QSqlError>
//3.創建連接
qDebug()<<"available driver:";
 QStringList drivers=QSqlDatabase::drivers();
 foreach(QString driver,drivers)
   qDebug()<<"/t"<<driver;
 QSqlDatabase db=QSqlDatabase::addDatabase("SQLITE");
 qDebug()<<"SQLITE driver?"<<db.isValid();
 QString dsn=QString::fromLocal8Bit("DRIVER={SQL SERVER};SERVER=192.168.0.123;DATABASE=test");      db.setHostName("192.168.0.123");
 db.setDatabaseName(dsn);
 db.setUserName("sa");
 db.setPassword("111111");
 if(!db.open())
 {
   qDebug()<<db.lastError().text();
    QMessageBox::critical(0,QObject::tr("Database Error"),db.lastError().text());
    returnfalse;
 }
//4.查詢數據
QSqlQuery query;
query.exec("select * from mytable");
while(query.next())
{
.........
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章