Sqlite3入门,安装和使用。
Win 7 + MSVC 2012 试用版
之所以用Sqlite,主要是因为,朋友不能在公司电脑上面安装东西,基于Mysql这种需要安装而且要起后台服务的程序自然都玩不了,那就Sqlite。
1、首先声明一下,完全没有必要安装,网上很多什么又是编译,又是什么生成lib的玩法,完全是绕路了(我觉得)。直接在工程里面把官方的C和H文件including进去就是了。我不知道其他人实际开发怎么玩的,有一点我知道,Qt的Sqlite3支持就是直接把源代码涵盖进去,而不是使用库再链接。
2、下载官网的源代码http://www.sqlite.com/download.html:
下载后,解压,如下:
- D:\Sqlite开发\源代码\sqlite-amalgamation-3071700>dir
- Volume in drive D is D
- Volume Serial Number is D8DC-109A
- Directory of D:\Sqlite开发\源代码\sqlite-amalgamation-3071700
- 2013/05/22 09:09 <DIR> .
- 2013/05/22 09:09 <DIR> ..
- 2013/05/20 13:56 99,401 shell.c
- 2013/05/20 13:56 4,973,863 sqlite3.c
- 2013/05/20 13:56 348,618 sqlite3.h
- 2013/05/20 13:56 25,974 sqlite3ext.h
- 4 File(s) 5,447,856 bytes
- 2 Dir(s) 37,436,293,120 bytes free
3、新建一个VS空工程,路径:D:\Qt_Proj\Sqlite_cons1,代码在D:\Qt_Proj\Sqlite_cons1\Sqlite_cons1路径下面,此时还没有代码,把步骤2里面的sqlite3.c和sqlite3.h拷贝过来,然后添加一个main文件:source.cpp。
4、完成程序功能,也就是source.cpp的实现代码:
- #include <stdio.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(){
- 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));
- sqlite3_close(db);
- return(1);
- }
- rc = sqlite3_exec(db, “create table if not exists work (first integer primary key autoincrement, second text)”, callback, 0, &zErrMsg);
- if( rc!=SQLITE_OK ){
- fprintf(stderr, “SQL error: %s\n”, zErrMsg);
- sqlite3_free(zErrMsg);
- }
- rc = sqlite3_exec(db, “insert into work(second) values (‘吃饭’)”, callback, 0, &zErrMsg);
- if( rc!=SQLITE_OK ){
- fprintf(stderr, “SQL error: %s\n”, zErrMsg);
- sqlite3_free(zErrMsg);
- }
- rc = sqlite3_exec(db, “insert into work(second) values (‘asdf’)”, callback, 0, &zErrMsg);
- if( rc!=SQLITE_OK ){
- fprintf(stderr, “SQL error: %s\n”, zErrMsg);
- sqlite3_free(zErrMsg);
- }
- sqlite3_close(db);
- return 0;
- }
5、运行程序,会生成test.db:
6、这个时候我们用Sqlite shell工具查看效果:
- D:\Qt_Proj\Sqlite_cons1\Sqlite_cons1>Sqlite3 test.db
- SQLite version 3.7.17 2013-05-20 00:56:22
- Enter “.help” for instructions
- Enter SQL statements terminated with a “;”
- sqlite> .table
- work
- sqlite> select * from work;
- 1|│╘╖╣╟δ░┤
- 2|asdf
- sqlite>
上面有乱码,是因为我的cmd我修改了字体和显示,以至于不能显示中文了。
7、再说明一下,编译的文件里面一个是cpp的,而Sqlite3的实现文件是.c文件,没有关系的,在sqlite3.h里面有这么一段:
- #ifndef _SQLITE3_H_
- #define _SQLITE3_H_
- #include <stdarg.h> /* Needed for the definition of va_list */
- /*
- ** Make sure we can call this stuff from C++.
- */
- #ifdef __cplusplus
- extern “C” {
- #endif