Embedded database sqlite3 learning

SQLite3 database learning



foreword

提示:这里可以添加本文要记录的大概内容:

The databases based on embedded Linux mainly include SQLite, Firebird, Berkeley DB, etc. Among them, the source code of sqlite is c, and its source code is completely open. The first A1pha version of SQLite was born in May 2000. He is a lightweight embedded database. SQLite has the following characteristics: zero configuration - no need to install and manage configuration; a complete database stored in a single disk file; database files can be freely shared between machines with different byte orders; support database size up to 2TB; small enough, all The source code is about 30,000 lines of c code, 250KB; it is faster than most popular databases to operate data;


提示:以下是本篇文章正文内容,下面案例可供参考

1. Installation method

sudo apt-get install sqlite3

Two, sqlite3 basic commands

1、系统命令(以‘.’开头的命令)
.help Help
.quit Exit
.exit Exit
.schema View the structure diagram of the table
2、sql命令
Basic sql commands do not .start with, but ;end with

1-- create a table
create table stuinfo(id integer, name text, age integer, score float);
2-- insert a record
insert into stuinfo values(1001, 'zhangsan', 18, 80);
insert into stuinfo ( id, name, score) values(1002, 'lisi', 90);

3-- View database records
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; query the specified field
select * from stuinfo where score >= 85 and score < 90;

4-- Delete a record
delete from stuinfo where id=1003 and name='zhangsan';

5-- Update a record
update stuinfo set age=20 where id=1003;
update stuinfo set age=30, score = 82 where id=1003;

6-- delete a table
drop table stuinfo;

7-- Add a column
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;

Database setting primary key:
create table info(id integer primary key autoincrement, name vchar);

3、sqlite3 数据库 C语言 API

int sqlite3_open(
const char filename, / Database filename (UTF-8) */
sqlite3 *ppDb / OUT: SQLite db handle */
);

Function: Open database
Parameters: filename database name
ppdb database handle
Return value: 0 for success SQLITE_OK, error code

int sqlite3_close(sqlite3* db);
Function: Close the database
Parameters:
Return value: 0 for success SQLITE_OK, error code

== const char sqlite3_errmsg(sqlite3 db);==
Function: Get the description of the error message

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 */
);

Function: Execute a sql statement
Parameters: db database handle
sql sql statement
callback callback function, only when querying, the parameter
arg is passed to the callback function as the parameter
errmsg error message
Return value: success SQLITE_OK

Query callback function:
int (callback)(void arg,int ncolumns ,char** f_value,char** f_name),/* Callback function */
Function: After the query statement is executed, this function will be called back
Parameters: arg Receive the parameters passed by sqlite3_exec
ncolumns number of columns
f_value column value address
f_name column name
return value: 0,

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);

查询

3. Simple student management system based on sqlite3

The code is as follows (example):

#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;
}

Guess you like

Origin blog.csdn.net/m0_57730390/article/details/126646595