一篇文章拿捏SQLite3数据库

本文介绍了SQLite3,一种轻量级的嵌入式数据库,其特点包括无服务器、零配置和高性能。文章详细讲解了SQLite在不同领域的应用,以及常用的命令和C语言API示例,包括数据库操作、命令执行和错误处理。
摘要由CSDN通过智能技术生成

技术笔记!

一、SQLite3简介

SQLite是一种轻量级的嵌入式数据库引擎,它是一个C库,不需要独立的服务器进程,将数据库引擎与应用程序直接连接在一起。SQLite数据库适用于许多不需要高并发和大规模数据处理的应用程序,如移动应用程序、桌面应用程序和小型Web应用程序等。

SQLite具有以下特点:

  1. 轻量级:SQLite库的代码非常轻量,库文件仅几百KB大小,非常适合嵌入到其他应用程序中。
  2. 无服务器:SQLite将数据库引擎与应用程序直接连接在一起,没有独立的服务器进程,无需配置和管理服务器。
  3. 零配置:SQLite不需要复杂的配置过程,创建一个数据库文件并连接即可开始使用。
  4. 高性能:SQLite使用单一文件存储整个数据库,查询和读写性能较高。
  5. 支持SQL:SQLite支持标准的SQL语法,可以使用SQL语句进行数据操作。

SQLite的应用领域包括移动应用程序、桌面应用程序、嵌入式系统、小型Web应用程序等。它被广泛应用于Android和iOS移动应用程序开发中,用于存储和管理应用程序的数据。

二、SQLite常用命令

1.系统库命令:

1.1 系统命令 都以'.'开头

 <*.db> 是要打开的数据库文件。若该文件不存在,则自动创建
显示所有命令
sqlite> .help
退出sqlite3
sqlite>.quit
显示当前打开的数据库文件
sqlite>.database
显示数据库中所有表名
sqlite>.tables
查看表的结构
sqlite>.schema  <table_name>

1.2 sql命令以‘;’结尾

       1-- 创建一张表
            create table stuinfo(id integer, name text, age integer, score float);
        
        2-- 插入一条记录
            insert into stuinfo values(1001, 'zhangsan', 18, 80);
            insert into stuinfo (id, name, score) values(1002, 'lisi', 90);

        3-- 查看数据库记录
            select * from stuinfo;
            select * from stuinfo where score = 80;
            select * from stuinfo where score = 80 and name= 'zhangsan';
            select * from stuinfo where score = 80 or name='wangwu';
            select name,score from stuinfo;  查询指定的字段
            select * from stuinfo where score >= 85 and score < 90;

        4-- 删除一条记录
            delete from stuinfo where id=1003 and name='zhangsan';

        5-- 更新一条记录
            update stuinfo set age=20 where id=1003;
            update stuinfo set age=30, score = 82 where id=1003;

        6-- 删除一张表
            drop table stuinfo;

        7-- 增加一列
            alter table stuinfo add column sex char;

        8-- 删除一列
            create table stu as select id, name, score from stuinfo;
            drop table stuinfo;
            alter table stu rename to stuinfo;

     数据库设置主键:
     create table info(id integer primary key autoincrement, name vchar);

三、SQLite数据库C语言API

(1) 打开数据库函数

int sqlite3_open(
      const char *filename,   /* Database filename (UTF-8) */
      sqlite3 **ppDb          /* OUT: SQLite db handle */
     );
    功能:打开数据库
    参数:filename  数据库名称
          ppdb      数据库句柄
    返回值:成功为0 SQLITE_OK ,出错 错误码

(2)   关闭数据库函数

int sqlite3_close(sqlite3* db);
    功能:关闭数据库
    参数:
    返回值:成功为0 SQLITE_OK ,出错 错误码

(3) 描述错误信息函数

const char *sqlite3_errmsg(sqlite3*db);
    功能:得到错误信息的描述

(4) 执行sql语句函数

int sqlite3_exec(
   sqlite3* db,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluated */
  int (*callback)(void* arg,int,char**,char**),  /* Callback function */
  void * arg,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
  );
  功能:执行一条sql语句
  参数:

        db  数据库句柄
        sql sql语句
        callback  回调函数,只有在查询时,才传参
        arg      为回调函数传递参数
        errmsg  错误消息
  返回值:成功 SQLITE_OK

(5)查询回调函数

int (*callback)(void* arg,int ncolumns ,char** f_value,char** f_name),  /* Callback function */
功能:查询语句执行之后,会回调此函数
参数:

        arg   接收sqlite3_exec 传递来的参数
        ncolumns 列数
        f_value 列的值得地址
        f_name   列的名称
返回值:成功返回0,失败返回-1;

(6)查询函数

int sqlite3_get_table(
  sqlite3 *db,          /* An open database */
  const char *zSql,     /* SQL to be evaluated */
  char ***pazResult,    /* Results of the query */
  int *pnRow,           /* Number of result rows written here */
  int *pnColumn,        /* Number of result columns written here */
  char **pzErrmsg       /* Error msg written here */
);

void sqlite3_free_table(char **result);                        //配套使用

功能:执行SQL操作

参数:
        db:数据库句柄
        sql:SQL语句
        resultp:用来指向sql执行结果的指针
        nrow:满足条件的记录的数目
        ncolumn:每条记录包含的字段数目
        errmsg:错误信息指针的地址
返回值:成功返回0,失败返回错误码

void sqlite3_free_table(char **result);

(7)案例演示

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

#define  DATABASE  "student.db"
#define  N  128

int do_insert(sqlite3 *db)
{
	int id;
	char name[32] = {};
	char sex;
	int score;
	char sql[N] = {};
	char *errmsg;

	printf("Input id:");
	scanf("%d", &id);

	printf("Input name:");
	scanf("%s", name);
	getchar();

	printf("Input sex:");
	scanf("%c", &sex);

	printf("Input score:");
	scanf("%d", &score);

	sprintf(sql, "insert into stu values(%d, '%s', '%c', %d)", id, name, sex, score);

	if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
	{
		printf("%s\n", errmsg);
	}
	else
	{
		printf("Insert done.\n");
	}

	return 0;
}
int do_delete(sqlite3 *db)
{
	int id;
	char sql[N] = {};
	char *errmsg;

	printf("Input id:");
	scanf("%d", &id);

	sprintf(sql, "delete from stu where id = %d", id);

	if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
	{
		printf("%s\n", errmsg);
	}
	else
	{
		printf("Delete done.\n");
	}

	return 0;
}
int do_update(sqlite3 *db)
{
	int id;
	char sql[N] = {};
	char name[32] = "zhangsan";
	char *errmsg;

	printf("Input id:");
	scanf("%d", &id);

	sprintf(sql, "update stu set name='%s' where id=%d", name,id);

	if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
	{
		printf("%s\n", errmsg);
	}
	else
	{
		printf("update done.\n");
	}

	return 0;
}


int callback(void *arg, int f_num, char ** f_value, char ** f_name)
{
	int i = 0;

	for(i = 0; i < f_num; i++)
	{
	//	printf("%-8s %s", f_value[i], f_name[i]);
		printf("%-8s", f_value[i]);
	}

	printf("++++++++++++++++++++++");
	putchar(10);

	return 0;
}

int do_query(sqlite3 *db)
{
	char *errmsg;
	char sql[N] = "select count(*) from stu where name='zhangsan';";

	if(sqlite3_exec(db, sql, callback,NULL , &errmsg) != SQLITE_OK)
	{
		printf("%s", errmsg);
	}
	else
	{
		printf("select done.\n");
	}
}

int do_query1(sqlite3 *db)
{
	char *errmsg;
	char ** resultp;
	int nrow;
	int ncolumn;

	if(sqlite3_get_table(db, "select * from stu", &resultp, &nrow, &ncolumn, &errmsg) != SQLITE_OK)
	{
		printf("%s\n", errmsg);
		return -1;
	}
	else
	{
		printf("query done.\n");
	}

	int i = 0;
	int j = 0;
	int index = ncolumn;

	for(j = 0; j < ncolumn; j++)
	{
		printf("%-10s ", resultp[j]);
	}
	putchar(10);

	for(i = 0; i < nrow; i++)
	{
		for(j = 0; j < ncolumn; j++)
		{
			printf("%-10s ", resultp[index++]);
		}
		putchar(10);
	}

return 0;
}

int main(int argc, const char *argv[])
{
	sqlite3 *db;
	char *errmsg;
	int n;
	
	if(sqlite3_open(DATABASE, &db) != SQLITE_OK)
	{
		printf("%s\n", sqlite3_errmsg(db));
		return -1;
	}
	else
	{
		printf("open DATABASE success.\n");
	}

	if(sqlite3_exec(db, "create table if not exists stu(id int, name char , sex char , score int);",
				NULL, NULL, &errmsg) != SQLITE_OK)
	{
		printf("%s\n", errmsg);
	}
	else
	{
		printf("Create or open table success.\n");
	}

	while(1)
	{
		printf("********************************************\n");
		printf("1: insert  2:query  3:delete 4:update 5:quit\n");
		printf("********************************************\n");
		printf("Please select:");
		scanf("%d", &n);

		switch(n)
		{
			case 1:
				do_insert(db);
				break;
			case 2:
				do_query(db);
			//	do_query1(db);
				break;
			case 3:
				do_delete(db);
				break;
			case 4:
				do_update(db);
				break;
			case 5:
				printf("main exit.\n");
				sqlite3_close(db);
				exit(0);
				break;
			default :
				printf("Invalid data n.\n");
		}

	}

	return 0;
}

  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值