Table of contents
(2) Add/delete/modify/check records
(4) Query results from the database
1. SQL commands
Commands are divided into system commands (commands starting with '.', generally used to operate on the current database) and common commands (commands ending with ';', generally used to operate tables in the database).
1. System commands
The following are sqlite3 system commands.
.backup ?DB? FILE Back up this database as a database/file format.bail
ON|OFF Stop when encountering an error (default off)
.databases List data information (name and path)
.dump ?TABLE? ... with Download the database in text format (if TABLE is selected, only the corresponding table will be downloaded)
.echo ON|OFF Turn on or off the command line echo.exit
Exit the program.header
(s) ON|OFF Turn on or off the header.help
Display help information
. import FILE TABLE Import the file FILE into the database
table.indices ?TABLE? Display the index name (when specifying the table name, display the index of the table)
.mode MODE ?TABLE? Set the output mode:
csv comma-separated
column left-aligned
html HTML code
insert SQL insert table statement
line one value per line
list set string separator
tabs set table separator
tcl TCL list element.quit
exit program.restore
?DB? FILE restore database or FILE
.schema ?TABLE? list database The structure of all tables (if there is a table name, only display the table structure)
.show Display the value of the current output mode setting.tables
?TABLE? List the table name (if there is a table name, only check whether the table exists)
.timeout MS to Try to control the table in milliseconds
. width NUM NUM ... Set the column width corresponding to the column in the output mode
2. Common commands
This section mainly describes creating/deleting tables, adding/deleting/modifying/checking records, adding/deleting a column, and setting primary keys.
(1) Create/delete table
1. Create a table
create table table name (field name 1 field type, field name 2 field type, ....);
例:create table TestTable(id int, name char, age int);
Note: The type of characters and strings is specified as char or text
2. Delete a table
drop table table name;
例:drop table TestTable;
(2) Add/delete/modify/check records
1. Add records
insert into table name values(field value 1, field value 2,...);
例:insert into TestTable values(1, 'Shimenglong', 25);
Note: This method must assign values in sequence according to the field names in the table, and each field cannot be omitted
例:insert into TestTable(id, name) values(2, 'Chen');
Note: In this method, some field values may not be specified, and unspecified fields may not be assigned values
2. Find records
select <find item> from table name <where search condition>;
Example: select * from TestTable; (find all records)
select * from TestTable where id=1; (find records for symbolic conditions)
select name from TestTable where id=2 and name='Chen'; (the string needs to be quoted)
select id from TestTable where name='Shimenglong' or age=20;
select id,name from TestTable; (only query id and name)
Note: You can view records with .headers on (display list name) .mode column (display content by column)
3. Delete records
delete from table name where search condition;
例:delete from TestTable where name='Shimenglong';
4. Update records
update table name set replacement item where search condition;
update TestTable set age=25 where name='Chen';
(3) Add/delete a column
1. Add a column
alter table table name add column field field type;
例:alter table TestTable add column Address text;
2. Delete a column
Note: sqlite3 does not allow deleting a column directly, you need to create a new table first, delete the old table, and rename the new table
Example: create table TestTableBak as select id , name from TestTable ; (create a new table)
drop table TestTable ; (drop old table)
alter table TestTableBak rename to TestTable ; (new table renamed to old table)
(4) Set the primary key
database primary key
Note: The field set as the primary key cannot be repeated, and the primary key is set when creating the database
create table table name (field field type primary key );
例:create table TestTableBak (id int primary key);
2. Common APIs
1. Function
(1) Open the database
原型:int sqlite3_open( const char *pFilename, sqlite3 **pDb );
parameter:
pFilename: database name;
pDb: the pointer to operate the database;
Return value: SQLITE_OK is returned on success, error_code is reset on failure, and error information can be obtained through sqlite3_errmsg;
example:
sqlite3 *db;
if(sqlite3_open("testDB.db", &db) != SQLITE_OK)
{
printf("错误:%s\n", sqlite3_errmsg(db));
exit(1);
}
(2) Close the database
原型:int sqlite3_close(sqlite3* pDb);
parameter:
pDb: the pointer to operate the database;
Return value: SQLITE_OK is returned on success, error_code is reset on failure, and error information can be obtained through sqlite3_errmsg;
example:
sqlite3_close(db);
(3) Execute a sql command
原型:int sqlite3_exec(sqlite3* pDb,const char *pSql,int (*callback)(void*,int,char**,char**), void *pArg, char **pzErrmsg );
parameter:
pDb: pointer to the database
pSql: the sql command to be executed
callback: callback function, only when querying statements, pass parameters to the callback function
原型:int (*callback)(void* arg ,int ncolumn ,char** f_value,char** f_name) ;
Function: Get query results. When sqlite3_exec queries, multiple records can be obtained, and sqlite3_exec will call the callback function multiple times according to the number of records. The callback function only obtains the content of a row of records queried by sqlite3_exec each time.
parameter:
arg: the parameter passed to the callback function
ncolumn: the column number of the field contained in the record
f_value: An array of pointers holding each field value
f_name: array of pointers holding each field name
Return value: success: 0; failure: not 0
pArg: Pass parameter for callback
pzErrmsg: the address of the error message
Return value: SQLITE_OK is returned on success, error_code is reset on failure, and error information can be obtained through sqlite3_errmsg;
example:
Execute a SQL command
sprintf(sql, "create table %s(id int, name char)", "test");
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
printf("错误:创建%s表失败<%s>\n", "test", errmsg);
else
printf("成功:创建%s表成功\n", "test");
Execute the callback function to find the data
int callback(void *arg, int ncolumn, char **text, char **name)
{
printf("查询结果: column = %d\n", ncolumn);
printf("id = %s, name = %s\n", text[0], text[1]);
return 0;
}
void get_message(sqlite3 *db)
{
char sql[128] = {0};
char *errmsg;
sprintf(sql, "select * from %s", "test");
if(sqlite3_exec(db, sql, callback, NULL, &errmsg) != SQLITE_OK)
printf("错误:查询%s表失败<%s>\n", "test", errmsg);
else
printf("成功:查询%s表成功\n", "test");
}
(4) Query results from the database
原型:int sqlite3_get_table( sqlite3 *pDb, const char *pSql, char ***pazResult, int *pnRow,
int *pnColumn, char **pzErrmsg );
parameter:
pDb: database operation handle
pSql: the sql statement of the database
pazResult: the result of the query (a new memory storage query information result has been created in the function, and the char** type pointer variable address can be passed here)
pnRow: the number of rows that meet the query conditions, rows that do not contain field names
pnColumn: the number of columns that meet the query conditions
pzErrmsg: error message
Return value: return 0 on success, reset error_code on failure, you can get error information through sqlite3_errmsg;
example:
void get_table(sqlite3 *db)
{
char sql[128] = {0};
char **ret;
int nrow, ncolumn;
char *errmsg;
sprintf(sql, "select * from %s where id = 1", "test");
if(sqlite3_get_table(db, sql, &ret, &nrow, &ncolumn, &errmsg) != SQLITE_OK)
printf("错误:查询%s表失败<%s>\n", "test", errmsg);
printf("row= %d, colum = %d\n", nrow, ncolumn);
int i, j, n = 0;
for(i = 0; i < nrow + 1; i++)
{
for(j = 0; j < ncolumn; j++)
printf("%-15s", ret[n++]);
putchar(10);
}
}
(5) Release memory
原型:void sqlite3_free_table(char **pzResult);
parameter:
pzResult: When calling the sqlite3_get_table function, apply for storage space for query information;
2. Pay attention
When using the sqlite3 API, in addition to adding header files, you need to add "-lsqlite3" to connect to the dynamic library when compiling, otherwise the compilation will report an error similar to "collect2: error: ld returned 1 exit status".
Summarize
The above is what I want to talk about today. This article only briefly introduces the use of sqlite3, and sqlite3 provides a large number of functions and methods that allow us to process data quickly and conveniently.