Sqlite3 C++ 使用方法

转载 2017年05月12日 11:15:19

需要在 C++ 程序中读写 sqlite3 数据库,查阅了一下资料,发现了一个简单实用教程。另外还有如何在windows下生成sqlite3静态库,生成好的sqlite3静态库可以在这里下载。


windows下生成sqlite3静态库

  1. 去 sqlite 官网下载页面下载源文件 sqlite-amalgamation-3180000.zip 。
  2. 在VS2013中,文件->新建->项目->Win32项目,命名为sqlite3(其他名称也行)。在向导设置中,选择DLL(D)、空项目。选择release x64模式。
  3. 将下载的sqlite-amalgamation-3180000.zip 中的“sqlite3.h”、“sqlite3.c”、“sqlite3ext.h”三个文件添加到工程中,具体做法:右键sqlite3工程->添加->现有项,在出现的对话框中选择上述三个文件。
  4. 编译生成sqlite3.dll文件,同时会在工程所在目录中产生sqlite3.obj文件。
  5. 接下来要用到VS安装目录下的lib.exe文件。将sqlite3.obj文件复制到lib.exe所在目录下,我的是C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64。
  6. 打开cmd窗口,转到lib.exe所在文件夹下。输入命令:lib sqlite3.obj。这时会生成静态的sqlite3.lib(大小为2.91MB)如果无法生成,可以试试用管理员权限运行cmd。
  7. 将sqlite3.lib和sqlite3.h添加到VS工程就可以使用sqlite啦。

SQLite C/C++ Tutorial

C/C++ Interface APIs

介绍三个主要的 API,知道这三个API就可以简单的使用sqlite3了。原tutotial写得非常清楚,我直接复制过来了。

  1. sqlite3_open(const char *filename, sqlite3 **ppDb)

    This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines.

    If the filename argument is NULL or ‘:memory:’, sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session.

    If filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name.

  2. sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)

    This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command.

    Here, first argument sqlite3 is open database object, sqlite_callback is a call back for which data is the 1st argument and errmsg will be return to capture any error raised by the routine.

  3. sqlite3_close(sqlite3*)

    This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection.

    If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements.


Connecting To Database

Following C code segment shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.

#include <stdio.h>
#include <sqlite3.h> 

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;

   rc = sqlite3_open("test.db", &db);

   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
   }
   sqlite3_close(db);
}

Now, let’s compile and run above program to create our database test.db in the current directory. You can change your path as per your requirement.

$gcc test.c -l sqlite3
$./a.out
Opened database successfully

If you are going to use C++ source code, then you can compile your code as follows:

$g++ test.c -l sqlite3

Here we are linking our program with sqlite3 library to provide required functions to C program. This will create a database file test.db in your directory and you will have the result something as follows:

-rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out
-rw-r–r–. 1 root root 323 May 8 02:05 test.c
-rw-r–r–. 1 root root 0 May 8 02:06 test.db


Create a Table

Following C code segment will be used to create a table in previously created database:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int  rc;
   char *sql;

   /* Open database */
   rc = sqlite3_open("test.db", &db);
   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   }else{
      fprintf(stdout, "Opened database successfully\n");
   }

   /* Create SQL statement */
   sql = "CREATE TABLE COMPANY("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "NAME           TEXT    NOT NULL," \
         "AGE            INT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "SALARY         REAL );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
   fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Table created successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When above program is compiled and executed, it will create COMPANY table in your test.db and final listing of the file will be as follows:

-rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out
-rw-r–r–. 1 root root 1207 May 8 02:31 test.c
-rw-r–r–. 1 root root 3072 May 8 02:31 test.db


INSERT Operation

Following C code segment shows how we can create records in our COMPANY table created in above example:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;

   /* Open database */
   rc = sqlite3_open("test.db", &db);
   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
   }

   /* Create SQL statement */
   sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "  \
         "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \
         "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "  \
         "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); "     \
         "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
         "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \
         "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
         "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Records created successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When above program is compiled and executed, it will create given records in COMPANY table and will display following two line:

Opened database successfully
Records created successfully


SELECT Operation

Before we proceed with actual example to fetch records, let me give a little detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration:

typedef int (*sqlite3_callback)(
void*,    /* Data provided in the 4th argument of sqlite3_exec() */
int,      /* The number of columns in row */
char**,   /* An array of strings representing fields in the row */
char**    /* An array of strings representing column names */
);

If above callback is provided in sqlite_exec() routine as the third argument, SQLite will call the this callback function for each record processed in each SELECT statement executed within the SQL argument.

Following C code segment shows how we can fetch and display records from our COMPANY table created in above example:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   fprintf(stderr, "%s: ", (const char*)data);
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;
   const char* data = "Callback function called";

   /* Open database */
   rc = sqlite3_open("test.db", &db);
   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
   }

   /* Create SQL statement */
   sql = "SELECT * from COMPANY";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When above program is compiled and executed, it will produce the following result:

Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0

Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0

Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0

Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully


UPDATE Operation

Following C code segment shows how we can use UPDATE statement to update any record and then fetch and display updated records from our COMPANY table:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   fprintf(stderr, "%s: ", (const char*)data);
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;
   const char* data = "Callback function called";

   /* Open database */
   rc = sqlite3_open("test.db", &db);
   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
   }

   /* Create merged SQL statement */
   sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \
         "SELECT * from COMPANY";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When above program is compiled and executed, it will produce the following result:

Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0

Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0

Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0

Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully


DELETE Operation

Following C code segment shows how we can use DELETE statement to delete any record and then fetch and display remaining records from our COMPANY table:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   fprintf(stderr, "%s: ", (const char*)data);
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;
   const char* data = "Callback function called";

   /* Open database */
   rc = sqlite3_open("test.db", &db);
   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
   }

   /* Create merged SQL statement */
   sql = "DELETE from COMPANY where ID=2; " \
         "SELECT * from COMPANY";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

When above program is compiled and executed, it will produce the following result:

Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0

Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0

Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully


Reference

  1. http://www.cnblogs.com/imoon/archive/2012/11/30/2796726.html
  2. https://www.tutorialspoint.com/sqlite/sqlite_c_cpp.htm

相关文章推荐

SQLite3使用方法大全(一)之常用命令

前言本小节主要涉及SQLite3常用命令,具体看下面表格。 SQLite3官网命令 举例1. 创建一个表: 2. 插入数据,显示,设置显示格式,重新显示: 3. 如果有多个表,我们想将C...

SQLite3使用方法大全(四)之数据库创建、附加、分离

数据库创建语法基本语法:sqlite3 [table_name] /* 例如创建test.db数据库: */ lu@lu$ sqlite3 test.db我们还可以这样查看是否已经创建数据库:sqli...

sqlite3 外键作用原理和使用方法

转自http://zjx2988.blog.163.com/blog/static/9791033120150554232742/ 1. sqlite3 默认为关闭外键限制的,如要打开,请执行如下命...

SQLite3使用方法大全(二)之数据类型

前言:SQLite 数据类型是一个用来指定任何对象的数据类型的属性。SQLite 中的每一列,每个变量和表达式都有相关的数据类型。您可以在创建表的同时使用这些数据类型。SQLite 使用一个更普遍的动...

Visual Studio 2010环境下Sqlite3加密版(由wxSqlite制作)使用方法

Sqlite3是著名的嵌入式数据库,应用之广就不多说了。本篇主要介绍如何使用加密功能。Sqlite3本身提供了加密的接口,但是加密功能并没有实现,用户要使用的话需要自己编写代码来实现加密功能。幸运的是...

sqlite3工具的使用方法详细解释

这个例子的环境虽然是windows,但mac os下同样适用。 mac os10.10.5下亲测,非常好用。 ps: mac os10.10.5下sqlite3工具本身是系统自带的...

sqlite3 使用方法以及加密处理

自己实现加解密接口函数 如果真要我从一份 www.sqlite.org 网上down下来的 sqlite3.c 文件,直接摸索出这些接口的实现,我认为我还没有这个能力。 好在网上还有一些代码已经实...
  • educast
  • educast
  • 2014年08月21日 12:07
  • 8302

SQLite3使用方法大全(三)之日期&时间

基本函数SQLite 支持以下五个日期和时间函数:上述五个日期和时间函数把时间字符串作为参数。时间字符串后跟零个或多个 modifiers 修饰符。strftime() 函数也可以把格式字符串作为其第...

python使用sqlite3时游标的使用方法

cursor就是一个Cursor对象,这个cursor是一个实现了迭代器(def__iter__())和生成器(yield)的MySQLdb对象,这个时候cursor中还没有数据,只有等到fetcho...
  • MTbaby
  • MTbaby
  • 2017年03月07日 16:55
  • 426

C++开发SQLite3的使用总结

首先,SQLite3的非常轻量级的
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Sqlite3 C++ 使用方法
举报原因:
原因补充:

(最多只允许输入30个字)