The Linux c language operates on the database of connection to the sqlite database
- 2020-04-02 02:05:03
- OfStack
#include<stdio.h>
#include<sqlite3.h>
int select_callback(void *data,int col_count,char **col_values,char **col_name)
{
//The function is called back once per record, and as many times as there are records
int i;
for(i=0;i<col_count;i++)
{
printf("%s=%sn",col_name[i],col_values[i]==0?"NULL":col_values[i]);
}
return 0;
}
int main(int argc,char **argv)
{
//Create database tables
const char *SQL1="create table users(id int PRIMARY KEY,name varchar(20),birthday datetime);";
//Insert data into the database
const char *SQL2="insert into users values(1,'myd','2013-10-9');";
const char *SQL3="insert into users values(2,'myd','2013-10-9');";
//Query data from the database
const char *SQL4="select * from users;";
char *ErrMsg=0;
int ret = 0;
//Connect to database
sqlite3 *db =0;
ret=sqlite3_open("./DataBase",&db);
if(ret != SQLITE_OK)
{
fprintf(stderr," Unable to open database :%s",sqlite3_errmsg(db));
return 1;
}
printf(" Database connection successful! n");
//Perform to build table
ret = sqlite3_exec(db,SQL1,0,0,&ErrMsg);
if(ret != SQLITE_OK)
{
fprintf(stderr,"SQL Error:%sn",ErrMsg);
sqlite3_free(ErrMsg);
}
//Execute the insert record SQL statement
ret = sqlite3_exec(db,SQL2,0,0,&ErrMsg);
if(ret !=SQLITE_OK)
{
printf(" Insert data successfully n");
}
ret = sqlite3_exec(db,SQL3,0,0,&ErrMsg);
{
printf(" Insert data successfully n");
}
//Query the data table contents
printf("Query the data table contentsn");
sqlite3_exec(db,SQL4,select_callback,0,&ErrMsg);
//Close the database
sqlite3_close(db);
db = 0;
printf(" Database closed successfully! n");
return 0;
}
CFLAGS=-L /usr/local/sqlite-autoconf-3070400/lib -I/usr/local/sqlite-autoconf-307040/include -lsqlite3
all: sqlite.o sqlite
sqlite:sqlite.o
gcc sqlite.o -o sqlite $(CFLAGS)
sqlite.o:sqlite.c
gcc -c sqlite.c $(CFLAGS)
clean:
rm -rf sqlite *.o