Home  >  Article  >  Database  >  VC6下SQLite数据库应用起步

VC6下SQLite数据库应用起步

WBOY
WBOYOriginal
2016-06-07 15:36:151119browse

SQLite 是一款非常适合嵌入式应用的数据库,小巧、快速和可靠。真正的开源免费,不保留任何版权( Public Domain )。它无需运行额外的服务器进程,用它来开发桌面数据库的应用,乎比 MS Access 更显得简洁。 【一 . 生成 SQLite 库文件】 新建 “C:\mylibs\


SQLite是一款非常适合嵌入式应用的数据库,小巧、快速和可靠。真正的开源免费,不保留任何版权(Public Domain)。它无需运行额外的服务器进程,用它来开发桌面数据库的应用,似乎比MS Access更显得简洁。


【一生成SQLite库文件】 
新建“C:\mylibs\libSQLite3”目录,将它作为我们的当前工作目录。 

(1)
SQLite的官方网站下载 

源代码 SQLite 3.8.0.2
http://www.sqlite.org/2013/sqlite-amalgamation-3080002.zip

DLL库文件

http://www.sqlite.org/2013/sqlite-dll-win32-x86-3080002.zip

命令行控制平台

http://www.sqlite.org/2013/sqlite-shell-win32-x86-3080002.zip


解压缩其中的库文件中“sqlite3.def”“sqlite3.dll”两个文件到“C:\mylibs\libSQLite3\” 
打开命令提示符窗口,用LIB命令生成用于连接(LINK)使用的lib文件
CD C:\mylibs\libSQLite3 
LIB /DEF:sqlite3.def /machine:IX86 
这样将生成“sqlite3.lib”“sqlite3.exp”两个文件。 

(2)
检查文件清单,此时“C:\mylibs\libSQLite3\”目录下应该有如下五个文件
sqlite3.def 
sqlite3.dll
sqlite3.exp
sqlite3.h 
sqlite3.lib 
【二编写示例程序】 
(1)打开VC6.0,创建一个空的“Win32控制台应用程序项目,名为“sqlitedemo”,在“D:\VCStudio\sqlitedemo”目录下。

(2)Project→Settings,在Link选项卡,“Category”选择“General”,在“Object/library modules”的最后填入“sqlite3.lib”,注意用空格分隔各项。

(3)“libSQLite3”目录及其包含的文件复制到我们的工程目录。再将“libSQLite3”目录下的“sqlite3.lib”“ sqlite3.dll”文件移动到工程目录下。

这样,在需要用到“sqlite”库的CPP文件顶部,加入一行:
#include "sqlite3.h"
然后,就可以在文件中调用sqlite3.dll里面的所有函数了。 

(4)建立示例数据库。打开控制台 sqlite3.exe,生成app.db:
sqlite> CREATE TABLE t1(c1 TEXT);
sqlite> INSERT INTO t1 VALUES('Hello World!');
sqlite> SELECT * FROM t1;
Hello World!
sqlite> .exit

复制app.db到工程目录下。

(5)新建“C++源文件,名为“sqlitedemo.cpp”,选择加入工程,编写代码 
#include  
#include  

#include ".\libSQLite3\sqlite3.h" 

static int _callback_exec(void * notused,int argc, char ** argv, char ** aszColName) 

    int i; 
    for ( i=0; i
    { 
        printf( "%s = %s\n", aszColName[i], argv[i] == 0 ? "NUL" : argv[i] ); 
    } 

    return 0; 


int main(int argc, char * argv[]) 

    const char * sSQL = "select * from t1;"; 
    char * pErrMsg = 0; 
    int ret = 0; 
    sqlite3 * db = 0; 
    
    ret = sqlite3_open("./app.db", &db); 

    if ( ret != SQLITE_OK ) 
    { 
        fprintf(stderr, "Could not open database: %s", sqlite3_errmsg(db)); 
        exit(1); 
    } 

    printf("Successfully connected to database\n"); 

    sqlite3_exec( db, sSQL, _callback_exec, 0, &pErrMsg ); 
    if ( ret != SQLITE_OK ) 
    { 
        fprintf(stderr, "SQL error: %s\n", pErrMsg); 
        sqlite3_free(pErrMsg); 
    } 

    sqlite3_close(db); 
    db = 0; 

    return 0; 


“Ctrl+F5”运行,结果:
Successfully connected to database
c1 = Hello World!
Press any key to continue

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn