前面两篇文章介绍了SQlite数据库的基本语法和命令,这篇文章主要介绍利用SQlite提供的C接口实现用C语言编程操作数据库。
在编程之前我们先来了解几个重要的接口函数 sqlite3_open,sqllite3_exec 和 sqlite3_close。
原型:int sqlite3_open(const char *filename, sqlite3 **ppDb)
该接口函数用来打开一个指向 SQLite 数据库文件的连接,返回一个用于其他 SQLite 程序的数据库连接对象。
如果没有名为 filename 的数据库文件,则创建一个名为 filename 的数据库文件。
如果已经存在名为filename的数据库文件,则打开该数据库文件。
返回值:(列举几个相对重要的返回值)
宏 | 值 | 含义 |
---|---|---|
SQLITE_OK | 0 | Successful result |
SQLITE_ERROR | 1 | SQL error or missing database |
SQLITE_INTERNAL | 2 | Internal logic error in SQLite |
SQLITE_PERM | 3 | Access permission denied |
SQLITE_ABORT | 4 | Callback routine requested an abort |
SQLITE_BUSY | 5 | The database file is locked |
SQLITE_LOCKED | 6 | A table in the database is locked |
SQLITE_NOMEM | 7 | A malloc() failed |
SQLITE_READONLY | 8 | Attempt to write a readonly database |
SQLITE_INTERRUPT | 9 | Operation terminated by sqlite3_interrupt() |
SQLITE_NOTADB | 26 | File opened that is not a database file |
SQLITE_ROW | 100 | sqlite3_step() has another row ready |
SQLITE_DONE | 101 | sqlite3_step() has finished executing |
原型:int sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)
该接口函数提供了一个执行 SQL 命令的快捷方式,SQL 命令由 sql 参数提供,可以由多个 SQL 命令组成。
参数 sqlite3 是打开的数据库对象名称;
参数sql作为SQL命令传入;
参数sqlite_callback 是一个回调;
参数data 作为回调函数sqlite_callback的第一个参数;
参数errmsg 用来保存SQL命令是错误信息。
原型:int sqlite3_close(sqlite3*)
该接口函数用来关闭之前调用 sqlite3_open() 打开的数据库连接。所有与连接相关的语句都应在连接关闭之前完成。
如果还有查询没有完成,sqlite3_close() 将返回 SQLITE_BUSY 禁止关闭的错误消息。
了解上面的几个函数接口之后,我们来写分析几个例子,帮助我们理解。
程序如下:
/*********************************************************************************
* Copyright: (C) 2017 Li Wanneng
* All rights reserved.
*
* Filename: dbt1.c
* Description: This file test test.db
*
* Version: 1.0.0(06/12/2017)
* Author: Li Wanneng
* ChangeLog: 1, Release initial version on "06/12/2017 03:13:53 PM"
*
********************************************************************************/
#include
#include
#include
/********************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
********************************************************************************/
int main (int argc, char **argv)
{
sqlite3 *db;
char *zErrMsg;
int rc;
rc = sqlite3_open("t1.db",&db);
if(rc < 0)
{
fprintf(stderr,"sqlite3_open failure:%s\n",sqlite3_errmsg(db));
exit(0);
}
else
{
fprintf(stderr,"sqlite3_open t1.db success.\n");
}
sqlite3_close(db);
return 0;
} /* ----- End of main() ----- */
编译运行
注意我们在编译的时候后面一定要链接sqlite的库,不然编译通不过的。关于如何制作sqlite3库我在前面博客中已经总结过了。
[lwn@localhost sqlite_test]$ gcc dbt1.c -o tdb1 -l sqlite3
[lwn@localhost sqlite_test]$ ./tdb1
sqlite3_open t1.db success.
/*********************************************************************************
* Copyright: (C) 2017 Li Wanneng
* All rights reserved.
*
* Filename: dbt2.c
* Description: This file insert db
*
* Version: 1.0.0(06/12/2017)
* Author: Li Wanneng
* ChangeLog: 1, Release initial version on "06/12/2017 04:18:13 PM"
*
********************************************************************************/
#include
#include
#include
/**************************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
*************************************************************************************/
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
int i;
for(i=0; iprintf(" %s = %s |",azColName[i],argv[i]?argv[i]:"NULL");
}
printf("\n");
return 0;
} /* ----- End of callback() ----- */
/********************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
********************************************************************************/
int main (int argc, char **argv)
{
sqlite3 *db;
char *zErrMsg = 0;
int ret;
char *sql;
/* Open database */
ret = sqlite3_open("test.db",&db);
if(ret)
{
fprintf(stderr,"open test.db failure:%s\n",sqlite3_errmsg(db));
exit(0);
}
else
{
fprintf(stdout,"open test.db success.\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 satement */
ret = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if(ret != SQLITE_OK)
{
fprintf(stderr,"SQL error:%s\n",zErrMsg);
}
else
{
fprintf(stdout,"Table create successfully\n");
}
sqlite3_close(db);
return 0;
} /* ----- End of main() ----- */
编译运行:
[lwn@localhost sqlite_test]$ gcc dbt2.c -o tdb2 -l sqlite3
[lwn@localhost sqlite_test]$ ./tdb2
open test.db success.
Table create successfully
[lwn@localhost sqlite_test]$ ls test.db
test.db
[lwn@localhost sqlite_test]$ sqlite3 test.db
SQLite version 3.6.16
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema/*查看创建的表*/
CREATE TABLE COMPANY(ID INT PRIMARY KEY NOT NULL,NAME TEXT NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(50),SALARY REAL);
sqlite>
程序如下:
/*********************************************************************************
* Copyright: (C) 2017 Li Wanneng
* All rights reserved.
*
* Filename: dbt3.c
* Description: This file used insert data into table test.db
*
* Version: 1.0.0(06/12/2017)
* Author: Li Wanneng
* ChangeLog: 1, Release initial version on "06/12/2017 04:45:51 PM"
*
********************************************************************************/
#include
#include
#include
/**************************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
*************************************************************************************/
static int callback (void *NotUsed, int argc, char **argv, char **azColName)
{
int i;
for(i=0; iprintf("%s = %s |",azColName[i],argv[i]?argv[i]:"NULL");
}
printf("\n");
return 0;
} /* ----- End of callback() ----- */
/********************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
********************************************************************************/
int main (int argc, char **argv)
{
sqlite3 *db;
char *zErrMsg = 0;
int ret;
char *sql;
/* Open database */
ret = sqlite3_open("test.db",&db);
if(ret)
{
fprintf(stderr,"open failure:%s\n",sqlite3_errmsg(db));
exit(0);
}
else
{
fprintf(stdout,"open test.db successfully.\n");
}
/* Create SQL satement */
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, 'Texa', 15000.00);"\
"INSERT INTO COMPANY(ID, NAME, AGE, ADDRESS, SALARY) VALUES(3, 'Teddy', 23, 'Norway', 25000.00);"\
"INSERT INTO COMPANY(ID, NAME, AGE, ADDRESS, SALARY) VALUES(4, 'Mark', 25, 'Rich-Mond', 65000.00);";
/* Exexute SQL satement */
ret = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if(ret != SQLITE_OK)
{
fprintf(stderr,"exec failure:%s\n",zErrMsg);
exit(0);
}
else
{
fprintf(stdout,"Records created successfully.\n");
}
sqlite3_close(db);
return 0;
} /* ----- End of main() ----- */
编译运行:
[lwn@localhost sqlite_test]$ gcc dbt3.c -o tdb3 -l sqlite3
[lwn@localhost sqlite_test]$ ./tdb3
open test.db successfully.
Records created successfully.
[lwn@localhost sqlite_test]$ sqlite3 test.db
SQLite version 3.6.16
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .mode colum/*竖行显示*/
sqlite> .header on /*显示头*/
sqlite> select * from COMPANY;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texa 15000.0
3 Teddy 23 Norway 25000.0
4 Mark 25 Rich-Mond 65000.0
sqlite>
程序如下:
/*********************************************************************************
* Copyright: (C) 2017 Li Wanneng
* All rights reserved.
*
* Filename: dbt4.c
* Description: This file used select data from table COMPANY
*
* Version: 1.0.0(06/12/2017)
* Author: Li Wanneng
* ChangeLog: 1, Release initial version on "06/12/2017 05:22:14 PM"
*
********************************************************************************/
#include
#include
#include
/**************************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
*************************************************************************************/
static int callback(void *data, int argc, char **argv, char **azColName)
{
int i;
fprintf(stderr,"%s\n",(const char*)data);
for(i=0; iprintf("%s = %s\n",azColName[i],argv[i]?argv[i]:"NULL");
}
printf("\n");
return 0;
} /* ----- End of callback() ----- */
/********************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
********************************************************************************/
int main (int argc, char **argv)
{
sqlite3 *db;
int ret;
char *sql;
char *zErrMsg;
char *data = "Callback function called.";
/* Open SQL statement */
ret = sqlite3_open("test.db", &db);
if(ret)
{
fprintf(stderr,"open test.db failed:%s\n",sqlite3_errmsg(db));
exit(0);
}
else
{
fprintf(stdout,"open database successfully.\n");
}
sql = "select * from COMPANY;";
/* Exexute SQL statement */
ret = sqlite3_exec(db, sql, callback, (void *)data, &zErrMsg);
if(ret != SQLITE_OK)
{
fprintf(stderr,"exec failure:%s\n",zErrMsg);
sqlite3_free(zErrMsg);
}
else
{
fprintf(stdout,"Operation done successfully.\n");
}
sqlite3_close(db);
return 0;
} /* ----- End of main() ----- */
编译运行:
[lwn@localhost sqlite_test]$ gcc dbt4.c -o tdb4 -l sqlite3
[lwn@localhost sqlite_test]$ ./tdb4
open 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 = Texa
SALARY = 15000.0
Callback function called.
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 25000.0
Callback function called.
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully.
通过上面几个例程相信大家已经看明白了,用C语言编程实现对SQlite数据库操作套路都一样,唯一的区别就是sql传入的命令不同。所以在学习编程实现数据库增删改查之前得先了解数据库的操作命令。