Sqlite3 C++ 使用方法
2017-05-12 11:15
399 查看
需要在 C++ 程序中读写 sqlite3 数据库,查阅了一下资料,发现了一个简单实用教程。另外还有如何在windows下生成sqlite3静态库,生成好的sqlite3静态库可以在这里下载。
在VS2013中,文件->新建->项目->Win32项目,命名为sqlite3(其他名称也行)。在向导设置中,选择DLL(D)、空项目。选择release x64模式。
将下载的sqlite-amalgamation-3180000.zip 中的“sqlite3.h”、“sqlite3.c”、“sqlite3ext.h”三个文件添加到工程中,具体做法:右键sqlite3工程->添加->现有项,在出现的对话框中选择上述三个文件。
编译生成sqlite3.dll文件,同时会在工程所在目录中产生sqlite3.obj文件。
接下来要用到VS安装目录下的lib.exe文件。将sqlite3.obj文件复制到lib.exe所在目录下,我的是C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64。
打开cmd窗口,转到lib.exe所在文件夹下。输入命令:lib sqlite3.obj。这时会生成静态的sqlite3.lib(大小为2.91MB)如果无法生成,可以试试用管理员权限运行cmd。
将sqlite3.lib和sqlite3.h添加到VS工程就可以使用sqlite啦。
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.
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.
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.
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
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
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
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:
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
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
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
https://www.tutorialspoint.com/sqlite/sqlite_c_cpp.htm
windows下生成sqlite3静态库
去 sqlite 官网下载页面下载源文件 sqlite-amalgamation-3180000.zip 。在VS2013中,文件->新建->项目->Win32项目,命名为sqlite3(其他名称也行)。在向导设置中,选择DLL(D)、空项目。选择release x64模式。
将下载的sqlite-amalgamation-3180000.zip 中的“sqlite3.h”、“sqlite3.c”、“sqlite3ext.h”三个文件添加到工程中,具体做法:右键sqlite3工程->添加->现有项,在出现的对话框中选择上述三个文件。
编译生成sqlite3.dll文件,同时会在工程所在目录中产生sqlite3.obj文件。
接下来要用到VS安装目录下的lib.exe文件。将sqlite3.obj文件复制到lib.exe所在目录下,我的是C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64。
打开cmd窗口,转到lib.exe所在文件夹下。输入命令:lib sqlite3.obj。这时会生成静态的sqlite3.lib(大小为2.91MB)如果无法生成,可以试试用管理员权限运行cmd。
将sqlite3.lib和sqlite3.h添加到VS工程就可以使用sqlite啦。
SQLite C/C++ Tutorial
C/C++ Interface APIs
介绍三个主要的 API,知道这三个API就可以简单的使用sqlite3了。原tutotial写得非常清楚,我直接复制过来了。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.
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.
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
http://www.cnblogs.com/imoon/archive/2012/11/30/2796726.htmlhttps://www.tutorialspoint.com/sqlite/sqlite_c_cpp.htm
相关文章推荐
- sqlite在c++中的使用方法
- windows mobile C++ 的SQLite使用方法
- C++使用sqlite的方法
- 使用C++模板封装SQLite(完整版)
- C++ typename 关键字的使用方法和注意事项
- 用Visual C++.NET使用GDI+的一般方法
- c++中函数指针的使用方法
- C++中的property库的的使用方法
- C++中四种类型转换运算符的使用方法
- C++中Static作用和使用方法
- C++中Static作用和使用方法
- 使用IDispatch::Invoke函数在C++中调用C#实现的托管类库方法
- C++指针使用方法解惑
- 转:使用IDispatch::Invoke函数在C++中调用C#实现的托管类库方法
- C++类型转换运算符的使用方法
- 使用IDispatch::Invoke函数在C++中调用C#实现的托管类库方法
- [C++]实验八:学习类的聚集使用方法
- C++指针使用方法(转)
- C++指针使用方法解惑
- Visual C++ Profile的简单使用方法