Database knowledge and database programming

The concept of database

A database is "a warehouse that organizes, stores and manages data according to the data structure". It is a collection of large amounts of data that is stored in a computer for a long time , organized, shareable, and managed in a unified manner.

A database is a warehouse for storing data. It has a large storage space and can store millions, tens of millions, or hundreds of millions of data. But the database does not store data randomly, there are certain rules, otherwise the query efficiency will be very low. Today's world is an Internet world full of data , filled with a lot of data. That is, the Internet world is the data world. There are many sources of data, such as travel records, consumption records, web pages viewed , messages sent, and so on.

Database classification

Common relational databases include: MySQL, SQL Server, Oracle, SQLite.

Small database: MySQL : Free product, memory storage engine used less.

Medium-sized databases: SQL Server : Microsoft's commercial product is a newly added storage engine to adapt to big data and other business products. Microsoft's SQL statements have good compatibility and high commercial maturity.

Large databases: Oracle : An in-memory computing-based relational database that provides applications with extremely short response times and high throughput.

Lightweight database: SQLite : A lightweight database designed for embedded, it is a relational database management system that complies with ACID .

No matter which database, its core is SQL statements: SQL (Structured Query Language: Structured Query Language) is used to manage relational database management systems (RDBMS). The scope of SQL includes data insertion, query, update, and deletion, database schema creation and modification, and data access control. Therefore, the focus of learning should be on how to use SQL statements to operate the database.

The source code of SQLite is C, and its source code is completely open. It is a lightweight embedded database.

SQLite有以下特性:
     零配置一无需安装和管理配置; 
     储存在单一磁盘文件中的一个完整的数据库; 
     数据库文件可以在不同字节顺序的机器间自由共享; 
     支持数据库大小至2TB(1024G = 1TB);足够小,全部源码大致3万行c代码,250KB; 
     比目前流行的大多数数据库对数据的操作要快;

database and tables

A database is a file, and a table is actually a container for storing data in a file. The database can be understood as an excel file, and the table is a data sheet in excel, and a database can have multiple database tables.

database operation

create database

A database is essentially a file, usually with db as the suffix. Use the sqlite3 command to create it before opening the sqlite command prompt. The command is as follows:

$ sqlite3 student.db

It can also be opened and created using the .open command.

sqlite>.open student.db

In the above two methods, if student.db exists, it will be opened directly, and if it does not exist, it will be created.

sqlite3 database system command:

Starting with '.', commonly used are:

.help View all supported commands

.quit exit

.tables View which tables are there

.schema stu2 view table structure

SQL statement

No matter which database, its core is the SQL statement, which can be understood as a database standard, and no matter what kind of database it is, it must be supported.

  • SQL statements in sqlite do not need to start with ., and normal input content will be parsed as SQL statements.

  • The keywords of SQL statements are not case-sensitive, but it is usually a convention to write keywords in uppercase.

  • The SQL statement ends with a semicolon in the sqlite command terminal, if you do not type; press Enter, the terminal will continue to wait for typing.

Example: adding, deleting, modifying and querying the student grade database

1"Create a table

create table stu(id int,name char,score float);

create table stu1(id int primary key, name char, score float);

Note: Set the id field as the primary key (unique in the table); there can only be one number whose id is a certain value

2" Delete a table

drop table <table_name>;

table_name the name of the table to drop

You can use .table to view what tables are in the library. schema stu2 table_name to view the table structure

3" Insert data into the table

//insert the standard type field

insert into <table_name> values(value1, value2,…);

eg: insert into stu values(1,"Zhang San",99.9);

//Insert only part of the field id name score

insert into stu(id,name) values(4,“xiaoming”)

4》 Find data

Query all records in the table:

select * from <table_name>;

(* means to query all values)

Query the records in the table according to the specified conditions:

select * from <table_name> where <expression>;

Example: select * from stu where id=2;

//Find all the data with id=2 from the table stu

select * from stu where id=2 and name='lisi';

//Find the data with id=2 and name=lisi from the table stu

select * from stu where id=1 or name='zhangsan';

//Find the data with id=1 and name is zhangsan from the table stu

select score from stu where name='LiSi' or id=3;

//A column that satisfies the condition

select name,score from stu where name='LiSi' or id=3;

//A certain two columns that meet the condition

select * from stu limit 5;

//Only query the first n records

select * from stu order by id desc;

//Sort by id from largest to smallest

5" modify (update) data

update <table_name> set <f1=value1>, <f2=value2>… where <expression>;

//Modify the expression data in a table to value1 data

update stu set id=10 where id=1;

//Change id=1 to id=10;

6" Add field

alter table <table> add column <field> <type> default …;

alter table stu add column class int default 1;

//(Indicates that a column of class is added, the default value is 1)

7" Delete field

(In fact, the database does not support directly deleting a field (and a column). If you want to delete a column, you need three steps)

1)create table student as select id,name,score from stu;

Create a student table and copy id, name, score from the stu table

2) drop table stu;

Delete the original stu table

3) alter table student rename to stu;

double naming

The last column with 1 is deleted.

8》Delete a line

delete from stu where value

sqlite programming

Header file: #include <sqlite3.h>

Compile: gcc sqlite1.c -lsqlite3

function

1.sqlite_open open database function

int sqlite3_open(char  *path, sqlite3 **db);
功能:打开sqlite数据库,如果数据库不存在则创建它
path: 数据库文件路径
db: 指向sqlite数据库句柄的指针
返回值:成功返回SQLITE_OK,失败返回错误码(非零值)
// 1、创建或打开数据库
    sqlite3 *db;    //db是  指向数据库句柄的指针
    // 失败返回非0值
    if (sqlite3_open("./student.db", &db) != 0)
    {
        fprintf(stderr,"err:%s\n",sqlite3_errmsg(db));
        return -1;
    }
    printf("数据库创建成功!\n");

2.int sqlite3_close Close the database function

int sqlite3_close(sqlite3 *db);
功能:关闭sqlite数据库
返回值:成功返回SQLITE_OK,失败返回错误码
       返回错误信息
 //关闭数据库
    sqlite3_close(db);
    return 0;

3.int sqlite3_exec execute sql statement interface function

int sqlite3_exec(
  sqlite3 *db,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluated */
  int (*callback)(void*,int,char**,char**),  /* Callback function */
  void *arg,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
);

功能:执行SQL操作
参数:
    db:数据库句柄
    sql:要执行SQL语句
    callback:回调函数(满足一次条件,调用一次函数,用于查询)
             再调用查询sql语句的时候使用回调函数打印查询到的数据
    arg:传递给回调函数的参数
    errmsg:错误信息指针的地址
返回值:成功返回SQLITE_OK,失败返回错误码

回调函数:
typedef int (*sqlite3_callback)(void *para, int f_num, 
         char **f_value, char **f_name);

功能:
     select:每找到一条记录自动执行一次回调函数
     para:传递给回调函数的参数(由 sqlite3_exec() 的第四个参数传递而来)
     f_num:记录中包含的字段数目
     f_value:包含每个字段值的指针数组(列值)
     f_name:包含每个字段名称的指针数组(列名)
返回值:成功返回SQLITE_OK,失败返回-1,每次回调必须返回0后才能继续下次回调
//2.创建表
    if(sqlite3_exec(db,"create table stu(id int primary key,\
    name char,score float);",NULL,NULL,&errmsg)!= SQLITE_OK)
    {
        fprintf(stderr,"err:%s\n",errmsg);
        return -1;
    }
    //3.插入数据  stu   3 
    int n;//插入学生个数
    int id;
    char name[32];
    float score;
    char sql[128];
    printf("please input number:");
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
         scanf("%d %s %f",&id,name,&score);
         sprintf(sql,"insert into stu values(%d,\"%s\",%f);",id,name,score);
         printf("sql:%s\n",sql);
         if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!= SQLITE_OK)
        {
          fprintf(stderr,"err:%s\n",errmsg);
           return -1;
       }
    }

    //4.查询插入的数据
     if(sqlite3_exec(db,"select * from stu;",callback,"hello",&errmsg)!= SQLITE_OK)
        {
          fprintf(stderr,"err:%s\n",errmsg);
           return -1;
       }

    //callback回调函数
    int callback(void *arg,int f_num,char **f_value,char **f_name)
    {
        printf("arg:%s\n",(char *)arg);
        for(int i=0;i<f_num;i++)
        {
            printf("%s ",f_name[i]);
        }
        putchar(10);
        for(int i=0;i<f_num;i++)
        {
            printf("%s ",f_value[i]);
        } 
        putchar(10);
        return 0;
    }    

4. sqlite3_get_table does not use callback function to execute SQL statement (only for query)

int sqlite3_get_table(sqlite3 *db, const  char  *sql, char ***resultp,  int *nrow,  int *ncolumn, char **errmsg);

功能:执行SQL操作
db:数据库句柄
sql:SQL语句
resultp:用来指向sql执行结果的指针
nrow:满足条件的记录的数目(但是不包含字段名(表头 id name score))
ncolumn:每条记录包含的字段数目
errmsg:错误信息指针的地址

返回值:成功返回SQLITE_OK,失败返回错误码
//sqlite3_get_table 专门用于查询 select
    char **sp=NULL;
    int nrow,lie;
    if(sqlite3_get_table(db,"select * from stu;",\
    &sp,&nrow,&lie,&errmsg) != SQLITE_OK)
    {
        fprintf(stderr,"err:%s\n",errmsg);
           return -1;
    }
    //打印查询到的信息
    int i,j,k=0;
    for(i=0;i<nrow+1;i++)
    {
        for(j=0;j<lie;j++)
        {
            printf("%s ",sp[k++]);
        }
        putchar(10);
    }

5.sqlite3_errmsg returns the error message defined by sqlite3

char *sqlite3_errmsg(sqlite3 *db);
 char *errmsg=NULL;
if(    )//容错判断
{
     fprintf(stderr,"err:%s\n",errmsg);
     return -1;
}

full code

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

int callback(void *arg,int f_num,char **f_value,char **f_name)
{
    printf("arg:%s\n",(char *)arg);
    for(int i=0;i<f_num;i++)
    {
        printf("%s ",f_name[i]);
    }
    putchar(10);
    for(int i=0;i<f_num;i++)
    {
        printf("%s ",f_value[i]);
    }
    putchar(10);
    return 0;
}

int main(int argc,const char *argv[])
{
    //1.创建或打开数据库
    sqlite3 *db;
    if(sqlite3_open("./student.db",&db) != SQLITE_OK)
    {
        fprintf(stderr,"err:%s\n",sqlite3_errmsg(db));
        return -1;
    }
    printf("sqlite3_open ok.\n");

    char *errmsg=NULL;
#if 0
    //2.创建表
    if(sqlite3_exec(db,"create table stu(id int primary key,\
    name char,score float);",NULL,NULL,&errmsg)!= SQLITE_OK)
    {
        fprintf(stderr,"err:%s\n",errmsg);
        return -1;
    }
    //3.插入数据  stu   3 
    int n;//插入学生个数
    int id;
    char name[32];
    float score;
    char sql[128];
    printf("please input number:");
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
         scanf("%d %s %f",&id,name,&score);
         sprintf(sql,"insert into stu values(%d,\"%s\",%f);",id,name,score);
         printf("sql:%s\n",sql);
         if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!= SQLITE_OK)
        {
          fprintf(stderr,"err:%s\n",errmsg);
           return -1;
       }
    }

    //4.查询插入的数据
     if(sqlite3_exec(db,"select * from stu;",callback,"hello",&errmsg)!= SQLITE_OK)
        {
          fprintf(stderr,"err:%s\n",errmsg);
           return -1;
       }
#endif    
    //sqlite3_get_table 专门用于查询 select
    char **sp=NULL;
    int nrow,lie;
    if(sqlite3_get_table(db,"select * from stu;",\
    &sp,&nrow,&lie,&errmsg) != SQLITE_OK)
    {
        fprintf(stderr,"err:%s\n",errmsg);
           return -1;
    }

    int i,j,k=0;
    for(i=0;i<nrow+1;i++)
    {
        for(j=0;j<lie;j++)
        {
            printf("%s ",sp[k++]);
        }
        putchar(10);
    }

    sqlite3_close(db);
    return  0;
}
编译:
gcc sqlite.c -o sqlite -lsqlite3

Guess you like

Origin blog.csdn.net/m0_74762280/article/details/128944436