C and C ++ development based on sqlite3 database-simple
Sqlite3 is a file database. After the database is created, a database file with the. DB suffix will be generated locally. I use SQLite maestro.exe
Tool to generate database files, this tool is easy to use, please Baidu for details.
The source code of this database can be directly downloaded and used from the official website: sqlite3.c sqlite3.h. This article adds the source code to our project.
First introduce the header file # include "sqlite3.h"
Int main ()
{
Sqlite3 * DB = NULL; // declare a database object
Int res = sqlite3_open ("test. DB", & dB); // open the database. The first parameter is the path of the database file. If it does not exist, create
If (res! = Sqlite_ OK ){
Printf ("Open dB failed. \ n ");
Return-1;
}
{
Char ** dbresult; // used to save the query result
Int nrow, ncolumn; // number of rows, number of Columns
Char * errmsg = NULL; // error message
Int index;
Char SQL [256] = {0}; // SQL statement
Int I;
Snprintf (SQL, sizeof (SQL), "% s", "select ID, name from T1"); // assume that table T1 already exists in the database.
Printf ("SQL = % s \ n", SQL );
Res = sqlite3_get_table (dB, SQL, & dbresult, & nrow, & ncolumn, & errmsg );
If (res! = Sqlite_ OK ){
Printf ("select failed. \ n ");
Printf ("res = % d, errmsg = % S. \ n", res, errmsg );
Sqlite3_free (errmsg); // release the memory
Sqlite3_close (& dB); // close the database
Return-1;
}
Sqlite3_free (errmsg); // release the memory
Printf ("nrow = % d, ncolumn = % d \ n", nrow, ncolumn );
Index = ncolumn; // skip the header index = 0; Do not skip the header
// Output content
For (I = 0; I <nrow; I ++ ){
Printf ("ID = % d, name = % s \ n", atoi (dbresult [Index]), dbresult [index + 1]);
Index + = ncolumn;
}
Sqlite3_free_table (dbresult); // release space
}
Sqlite3_close (& dB); // close the database
Return 0;
}
In this example, you only need to open the database, retrieve the content, output the content, and close the database.