当前位置:网站首页>C language operation database (SQLite3) call interface function
C language operation database (SQLite3) call interface function
2022-06-12 18:17:00 【Winter snow is like spring】
C First, we need to have a database , So we need to create a database ,
stay linux In the environment sqlite3 In mode , By the way, write the database name at the end :
First, define a database pointer type , And then call the database. The interface function :sqlite3_open(“ Database name ”, Pointer address )”, The functionality : Open a database , If the database file does not exist , Automatically create , The command to open or create the database will be cached , It will not be executed until the database is actually called . And let the pointer defined above point to the database .ret Variable is used to receive the return value of this interface function , The return value of this function is zero SQLITE_OK Its value is 0, Indicates that the opening is successful , If not , Then you have to report an error . Let's judge 
At this point, we will open the database and complete the operation , We will start to create tables in the database , Because there is no table where to insert the data , good , To create table.
Here is a judgment on the return value of the create table function , If the return value is not SQLITE_OK This will result in unsuccessful table creation .
The above figure shows the function of creating a table , The function parameter is to pass a pointer to the database , The red mark 1 The string is the string used to create the table sql sentence , These three words are added here , This is to ensure that the existing errors in this table will not be reported when the code is executed in the future , This sentence means , establish mytable Table of , If the table exists, it will not be created , Just use it , If it doesn't exist, create it . The red mark 2 Is to call the database interface function , This function can do several things .
The function interface prototype is :
int sqlite3_exec(sqlite3 *db, const char *sql, sqlite3_callback callback, void *,char **errmsg);
db: Called database
sql:sql sentence
callback: Callback function , Every successful execution sql Statement is executed once callback function
void *: Parameters passed to the callback function ( Here, when you need to use , You need to cast )
errmsg: error message
After creating the database and tables above , We will start to insert data later , Pay attention here , When inserting, the field names should be in the same order as when creating the table in the previous step .
The image above sql What is defined is an array , When creating tables sql What is defined is a character pointer , Note that these two usages are different, although they both represent sql sentence , The one that creates the table points directly to sql sentence , In fact, it refers to the first address of the string , here sql It's for sprintf() Inside the function . This function takes the third parameter , Put it in the second parameter , Then put the second parameter in the first parameter , So here we need to use an array to take this string of characters , This is why this step is necessary , This is because we have to input the data we want to input , So this step is necessary .
Interface functions are also used later sqlite3_exec() function , This function can be used to create tables , insert data , Delete data , Display the data
The function here is similar to that of creating tables , Is to insert data into this database , If successful, proceed to the next step , If unsuccessful, an error message is returned .
After the insertion is completed, you can view , Look at the picture below :
The figure above shows that the data in the table will use the callback function parameter , there display It's a callback function , hinder (void *)&flag For callback function , The reason for taking the address here is that it needs to be changed flag Value , So send the address , See the following figure for this callback function :
The callback function here is to display the output table Data in .
After the display, delete the data in the database .
This is similar to the one used above ,sql The sentence has changed , Change some more hints
Here's how to use sqlite3_get_table() The function interface 
What we're going to use is sqlite_get_table() The prototype of the function is :
int sqlite3_get_table(
sqlite3 *db, // Handle to the open database
const char *zSql, // Executes SQL sentence
char pazResult, // The result is written to the char
int *pnRow, // Number of rows in the result set
int *pnColumn, // Number of columns in the result set
char **pzErrmsg // error message
);
And then perform the output display operation .
Okay , Almost that much , end . Paste the source code .
#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
// Call the database interface API
// Create table
int create_table(sqlite3 *pdb)
{
char *sql = NULL;
char *errmsg = NULL;
int ret;
sql = "create table if not exists mytable (id integer primary key,name text);";
ret = sqlite3_exec(pdb,sql,NULL,NULL,&errmsg);
if(SQLITE_OK != ret)
{
printf("create table error! %s\n",errmsg);
return -1;
}
else
{
return SQLITE_OK;
}
}
// insert data
int insert_record(sqlite3 *pdb)
{
char sql[100];
char *errmsg = NULL;
int ret;
int id;
char name[20];
printf("please input id and name: \n");
scanf("%d",&id);
scanf("%s",name);
// take id and name Print in string , Save in sql in
sprintf(sql,"insert into mytable (id,name) values (%d,'%s');",id, name);
ret = sqlite3_exec(pdb,sql,NULL,NULL,&errmsg);
if(SQLITE_OK != ret)
{
perror("insert error!");
printf("insert record 1 error! %s\n",errmsg);
return -1;
}
/* else { return SQLITE_OK; }*/
return SQLITE_OK;
}
// Callback function , The function name and parameter name are variable , But the return value type , Parameter type , The number and position of parameters cannot be changed .
// Callback function 1 The fourth parameter in the callback function 2 The column number of the table
// 3 An array of pointers to query results 4 An array of pointers to the header name
int display(void *para, int ncol, char *col_val[], char **col_name)
{
int i;
int *flag = NULL;
flag = (int *)para;
if(0 == *flag)
{
*flag = 1;
// Number of output columns
printf("column number is: %d\n", ncol);
for(i = 0; i < ncol; i++)
{
printf("%10s",col_name[i]);
}
printf("\n");
}
for(i = 0; i < ncol; i++)
{
printf("%10s",col_val[i]);
}
printf("\n");
return 0;
}
// Show
int inquire_uscb(sqlite3 *pdb)
{
char *sql = NULL;
char *errmsg = NULL;
int ret;
int flag = 0;
sql = "select * from mytable;";
// database , Statement string , Callback function , User entered parameters , Finally, it is passed to the callback function for use , error message
ret = sqlite3_exec(pdb,sql,display,(void *)&flag,&errmsg);
if(SQLITE_OK != ret)
{
printf("select error! %s\n",errmsg);
return -1;
}
else
{
return SQLITE_OK;
}
}
// Delete
int delete_record(sqlite3 *pdb)
{
char sql[100];
char *errmsg = NULL;
int ret;
int id;
printf("please input delete id:\n");
scanf("%d",&id);
sprintf(sql,"delete from mytable where id = %d;", id);
ret = sqlite3_exec(pdb,sql,NULL,NULL,&errmsg);
if(SQLITE_OK != ret)
{
printf("delete error! %s\n",errmsg);
return -1;
}
else
{
return SQLITE_OK;
}
}
// Show
int inquire_nocb(sqlite3 *pdb)
{
char *sql = NULL;
char ** ret_val = NULL;
char *errmsg = NULL;
int nrow;
int ncol;
int ret;
int i;
sql = "select * from mytable";
ret = sqlite3_get_table(pdb, sql, &ret_val, &nrow, &ncol, &errmsg);
if(SQLITE_OK == ret)
{
printf("nrow = %d ncol = %d\n",nrow,ncol);
for(i = 0; i < (nrow + 1)* ncol; i++ )
{
printf("%10s",ret_val[i]);
if((i + 1) % ncol == 0)
{
printf("\n");
}
}
}
else
{
sqlite3_free_table(ret_val);
return -1;
}
sqlite3_free_table(ret_val);
}
int main(int argc, char **argv)
{
sqlite3 *pdb; // Define a database pointer
int ret; // Pick up sqlite3_open() The return value of the function
ret = sqlite3_open("mydatabase.db",&pdb); // Open database , Let the pointer point to the database
if(ret != SQLITE_OK) // Judge whether the database is opened successfully
{
// Prompt open failed and return error description information
printf("open database fail! %s\n",sqlite3_errmsg(pdb));
exit(1);
}
else
{
printf("open database successfully!\n");
}
// The above is to open the database
// After opening the database, create a table
if(SQLITE_OK == create_table(pdb))
{
printf("create table success!\n");
}
else
{
sqlite3_close(pdb);
return 0;
}
// The above is to create a table , Later, we need to insert data into it
if(0 != insert_record(pdb))
{
sqlite3_close(pdb);
exit(-1);
}
// The above is the insert data , It should be shown later
// Show
inquire_uscb(pdb);
// Delete
delete_record(pdb);
// Show
inquire_nocb(pdb);
// Close the database
sqlite3_close(pdb);
return 0;
}
边栏推荐
- Use applet to quickly generate app in seven steps
- VirtualLab basic experiment tutorial -6 Blazed grating
- VirtualLab基础实验教程-6.闪耀光栅
- USB to serial port - maximum peak serial port baud rate vs maximum continuous communication baud rate
- When openharmony meets openeuler
- The server time zone value ‘� й ��� ʱ ��‘ is unrecognized or represents more than one time zone. ......
- Gossip about the 88 of redis source code
- VirtualLab basic experiment tutorial -5 Poisson bright spot
- Pytest automated testing framework (II)
- Vant3+ts dropdownmenu drop-down menu, multi data can be scrolled
猜你喜欢

An easy-to-use IDE for small programs

迄今微软不同时期发布的SQL Server各版本之间的大致区别,供参考查阅

PHP:Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocat

1.5 what is an architect (serialization)

Gospel of audio and video developers, rapid integration of AI dubbing capability

Global lock, table lock, row lock

Variable of C #

从源码解析 MobX 响应式刷新机制

js两数之和

PHP:Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocat
随机推荐
JS sum of two numbers
Stream flow precautions
JS中的栈(含leetcode例题)<持续更新~>
机器学习系列(5):朴素贝叶斯
Explanation of core interrupt of Godson processor
Vant3 +ts packaged simple step advancer component
Lightweight and convenient small program to app technology solution to realize interconnection with wechat / traffic app
Schematic diagram of active differential crystal oscillator and differences among lv-pecl, LVDS and HCSL
MIPS general purpose register + instruction
Queue priority of message queue practice
This shift, I still have to go
A method of quickly reusing wechat login authorization in app
Eve-ng installation (network device simulator)
leetcode 647. 回文子串
Make good use of IDE, speed up R & D efficiency by 100%
Strings in JS (including leetcode examples) < continuous update ~>
Leetcode151 flipping words in strings
Lambda - 1
ftrace
赛程更新| 2022微软与英特尔黑客松大赛火热报名中