YouTip LogoYouTip

Sqlite C Cpp

# SQLite – C/C++ ## Installation Before using SQLite in a C/C++ program, we need to ensure that the SQLite library is already present on the machine. You can refer to the SQLite installation section for the installation process. ## C/C++ Interface API The following are important C/C++ / SQLite interface routines that can meet your needs for using the SQLite database in C/C++ programs. If you need more details, please check the official SQLite documentation. | Serial Number | API & Description | | --- | --- | | 1 | **sqlite3_open(const char *filename, sqlite3 **ppDb)** This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines. If the _filename_ parameter is NULL or ':memory:', then sqlite3_open() will create an in-memory database in RAM that will only exist for the duration of the session. If the filename is not NULL, then sqlite3_open() will use this parameter value to try to open the database file. If the file with that name does not exist, sqlite3_open() will create a new database file with that name and open it. | | 2 | **sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)** This routine provides a shortcut for executing SQL commands provided by the sql parameter, which can consist of multiple SQL commands. Here, the first parameter _sqlite3_ is the opened database object, _sqlite_callback_ is a callback, _data_ is passed as its first argument, and errmsg will be returned to get any error messages generated by the program. The sqlite3_exec() routine parses and executes each command given by the **sql** parameter until the string ends or an error occurs. | | 3 | **sqlite3_close(sqlite3*)** This routine closes a database connection previously opened by sqlite3_open(). All associated statements should be completed before closing the connection. If there are still queries that haven't been completed, sqlite3_close() will return an SQLITE_BUSY error message prohibiting closure. | ## Connecting to a Database The following C code segment shows how to connect to an existing database. If the database does not exist, it will be created, and finally, a database object will be returned. ```c #include #include int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; rc = sqlite3_open("test.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %sn", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stderr, "Opened database successfullyn"); } sqlite3_close(db); } Now, let's compile and run the above program to create our database **test.db** in the current directory. You can change the path as needed. ```bash $gcc test.c -l sqlite3 $./a.out Opened database successfully If you want to use C++ source code, you can compile the code as shown below: ```bash $g++ test.c -l sqlite3 Here, we link our program with the sqlite3 library to provide the necessary functions to the C program. This will create a database file test.db in your directory, and you will get the following result: ```bash -rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out -rw-r--r--. 1 root root 323 May 8 02:05 test.c -rw-r--r--. 1 root root 0 May 8 02:06 test.db ## Creating a Table The following C code segment will be used to create a table in the previously created database: ```c #include #include #include static int callback(void *NotUsed, int argc, char **argv, char **azColName){ int i; for(i=0; i<argc; i++){ printf("%s = %sn", azColName, argv ? argv : "NULL"); } printf("n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %sn", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stdout, "Opened database successfullyn"); } /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" "ID INT PRIMARY KEY NOT NULL," "NAME TEXT NOT NULL," "AGE INT NOT NULL," "ADDRESS CHAR(50)," "SALARY REAL );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %sn", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "Table created successfullyn"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will create the COMPANY table in the test.db file, and the final file list will be as follows: ```bash -rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out -rw-r--r--. 1 root root 1207 May 8 02:31 test.c -rw-r--r--. 1 root root 3072 May 8 02:31 test.db ## INSERT Operation The following C code segment shows how to create records in the COMPANY table created above: ```c #include #include #include static int callback(void *NotUsed, int argc, char **argv, char **azColName){ int i; for(i=0; i<argc; i++){ printf("%s = %sn", azColName, argv ? argv : "NULL"); } printf("n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %sn", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stderr, "Opened database successfullyn"); } /* Create SQL statement */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %sn", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "Records created successfullyn"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will create the given records in the COMPANY table and will display the following two lines: ```bash Opened database successfully Records created successfully ## SELECT Operation Before we start with the examples of fetching records, let's understand some details about the callback function, which will be used in our examples. This callback provides a way to get results from a SELECT statement. It is declared as follows: ```c typedef int (*sqlite3_callback)(void*, /* Data provided in the 4th argument of sqlite3_exec() */ int, /* The number of columns in row */ char**, /* An array of strings representing fields in the row */ char** /* An array of strings representing column names */ ); If the above callback is passed as the third argument to the sqlite_exec() routine, then SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument. The following C code segment shows how to fetch and display records from the COMPANY table created above: ```c #include #include #include static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i=0; i<argc; i++){ printf("%s = %sn", azColName, argv ? argv : "NULL"); } printf("n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %sn", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stderr, "Opened database successfullyn"); } /* Create SQL statement */ sql = "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %sn", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "Operation done successfullyn"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will produce the following result: ```bash Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ## UPDATE Operation The following C code segment shows how to use the UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table: ```c #include #include #include static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i=0; i<argc; i++){ printf("%s = %sn", azColName, argv ? argv : "NULL"); } printf("n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %sn", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stderr, "Opened database successfullyn"); } /* Create merged SQL statement */ sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %sn", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "Operation done successfullyn"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will produce the following result: ```bash Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 25000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ## DELETE Operation The following C code segment shows how to use the DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table: ```c #include #include #include static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i=0; i<argc; i++){ printf("%s = %sn", azColName, argv ? argv : "NULL"); } printf("n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %sn", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stderr, "Opened database successfullyn"); } /* Create merged SQL statement */ sql = "DELETE from COMPANY where ID=2; " "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %sn", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "Operation done successfullyn"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will produce the following result: ```bash Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully
← Sqlite JavaSqlite Functions β†’