Application of combining SQLite3 with C/C ++

Source: Internet
Author: User
Tags sqlite db

SQLite is not ready for use at a time. Only downloading these things cannot be put into vs2010 and used immediately. The downloaded files include sqlite3.c/h/dll/def, which is not enough. The sqlite3.lib file we need is not in it, and we need to do it ourselves.
The visual studio Command Prompt tool provided by Visual Studio is used here. After opening, enter the directory containing sqlite3.dll and sqlite3.def, and enter the following command:
LIB/DEF: sqlite3.def/MACHINE: IX86
You can generate the sqlite3.exp and sqlite3.lib files, so that you can add the lib file to the Project for compilation.

SEC 1:
This time, an empty win32 project SQLite3Test is created under vs2010 to add a reference of sqlite3.lib in the project properties-link-input. Add the new file main. cpp, write a main function, and compile it.
Well, next, put sqlite3.h/def/exp/lib in the directory of SQLite3Test \ SQLite3Test \, which is associated with main. cpp,

Put sqlite3.dll together with the generated exe.
SEC 2:
Next we will start using sqlite3. Introduce the sqlite3.h header file and write the following code:
# Include <iostream>
# Include "sqlite3.h"
 
Using namespace std;
 
Int main (int argc, char ** argv)
{
Sqlite3 * conn = NULL;
Char * err_msg = NULL;
Char SQL [200] = "";
 
// Open the database and create a connection
If (sqlite3_open ("test. db", & conn )! = SQLITE_ OK)
{
Printf ("cannot be opened! ");
}
 
// Close the connection.
If (sqlite3_close (conn )! = SQLITE_ OK)
{
Printf ("unable to close, error code: % s \ n", sqlite3_errmsg (conn ));
Exit (-1 );
}
 
Printf ("operation successful! \ N ");
 
Return 0;
}
The function prototype of sqlite3_open is as follows:
SQLITE_API int sqlite3_open (
Const char * filename,/* Database filename (UTF-8 )*/
Sqlite3 ** ppDb/* OUT: SQLite db handle */
);
The function is self-evident. Open the database.
The first parameter is the name of the database file. If it does not exist, a database file is automatically created.
The second parameter is the pointer to the instance handle of sqlite3 .. (I think of it here. When I wrote mysql's C ++ api in linux, I also used a double pointer to let me die ..)
As the saying goes: "If it is enabled, it will be closed !", Therefore, sqlite3_close () plays this role.
However, the prototype of sqlite3_close is as follows:
SQLITE_API int sqlite3_close (sqlite3 *); // pay special attention to the dual pointer and common pointer ..
With the above example, you must have some knowledge about initialization. After running, a test. db file is added to the Debug directory, but the size is 0 kb, because the wood has content!
SEC 3:
Create a table in the database and insert data. Write the following code between open and close:
// Execute SQL
Sprintf (SQL, "CREATE TABLE test_for_cpp \
(Id int, name varchar (20), age int )");
If (sqlite3_exec (conn, SQL, NULL, NULL, & err_msg )! = SQLITE_ OK)
{
Printf ("operation failed, error code: % s", err_msg );
Exit (-1 );
}
 
// Add 10 records
For (int I = 0; I <10; I ++)
{
// Execute SQL
Sprintf (SQL, "INSERT INTO test_for_cpp \
(Id, name, age) VALUES \
(% D, '% s', % d) ", I," testPeople ", I );
If (sqlite3_exec (conn, SQL, NULL, NULL, & err_msg )! = SQLITE_ OK)
{
Printf ("operation failed, error code: % s", err_msg );
Exit (-1 );
}
}
The prototype of sqlite3_exec is as follows:
SQLITE_API int sqlite3_exec (
Sqlite3 *,/* An open database */
Const char * SQL,/* SQL to be evaluated */
Int (* callback) (void *, int, char **, char **),/* Callback function */
Void *,/* 1st argument to callback */
Char ** errmsg/* Error msg written here */
);
The first parameter is the sqlite3 instance.
The second parameter is the SQL statement to be executed.
The third parameter is the pointer of the callback function. The callback function is not required because only tables are created and data is inserted, and no data is returned. Use NULL instead.
The fourth parameter is the parameter used by the callback function. Same as the third.
The fifth parameter is the error message.
After running this operation, we can see that test. db is no longer 0 kb.

SEC 4:
Again, "if there is an insert, there will be a read !" Read the data in the database file.
I just mentioned the sqlite3_exec callback function. Now I need this function. First declare a callback function:
Int sqlite3_exec_callback (void * data, int nColumn,
Char ** colValues, char ** colNames );
The type of the four parameters cannot be changed.
Then write down the implementation of the callback function:
Int sqlite3_exec_callback (void * data, int nColumn, char ** colValues, char ** colNames)
{
For (int I = 0; I <nColumn; I ++)
{
Printf ("% s \ t", colValues [I]);
}
Printf ("\ n ");
 
Return 0;
}
Next, write the following statement after the insert entry statement:
// Query
Sprintf (SQL, "SELECT * FROM test_for_cpp ");
Sqlite3_exec (conn, SQL, & sqlite3_exec_callback, 0, & err_msg );
TIP: you can comment out the code for creating a table or inserting data first. Otherwise, 10 pieces of data will be inserted once, which may cause some troubles.
Run the command to view the result:

This callback function is called every time a piece of data is retrieved from the database. This is the most time-consuming process and the code should be as efficient as possible.
This is just a simple example, but it is enough for niche software. For some advanced usage such as sqlite3_db_mutex (read/write mutex lock) and sqlite3_backup_step (differential backup), you can take a look at the official sqlite3 tutorial (Stamp transfer ).
By satanness

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.