位置:首頁 > 數據庫 > SQLite教學 > SQLite C/C++

SQLite C/C++

安裝

在我們開始之前,我們需要在我們的C/ C + +程序中使用SQLite,以確保我們有SQLite庫設立在機器上。可以查看SQLite的安裝章節,以了解安裝過程。

C/C++ 接口API

以下是重要的C&C++/ SQLite 的接口程序就足夠SQLite數據庫從C/ C + +程序的使用需求。如果正在尋找一個更複雜的應用程序,那麼可以看到 SQLite 的官方文檔。

S.N. API & 描述
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 argument is NULL or ':memory:', sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session.

If filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name.

2 sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)

This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command.

Here, first argument sqlite3 is open database object, sqlite_callback is a call back for whichdata is the 1st argument and errmsg will be return to capture any error raised by the routine.

The sqlite3_exec() routine parses and executes every command given in the sql argument until it reaches the end of the string or encounters an error.

3 sqlite3_close(sqlite3*)

This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection.

If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements.

連接到數據庫

下麵的C代碼段顯示了如何連接到一個現有的數據庫。如果數據庫不存在,那麼它就會被創建,終於將返回一個數據庫對象。

#include <stdio.h>
#include <sqlite3.h> 

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: %s
", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully
");
   }
   sqlite3_close(db);
}

現在,讓我們來編譯和運行上麵的程序在當前目錄中創建我們的數據庫test.db。按要求可以改變路徑。

$gcc test.c -l sqlite3
$./a.out
Opened database successfully

如果要使用C++源代碼,可以編譯你的代碼如下:

$g++ test.c -l sqlite3

在這裡,把我們的程序及sqlite3的庫,以提供必要的C程序函數。這將創建一個數據庫文件test.db 並且在目錄結果有如下的內容:

-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

創建表

下麵的C代碼段將被用於先前創建的數據庫中創建一個表:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s
", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("
");
   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: %s
", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stdout, "Opened database successfully
");
   }

   /* 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: %s
", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Table created successfully
");
   }
   sqlite3_close(db);
   return 0;
}

上述程序編譯和執行時,它會創建 test.db 文件和最終列出 COMPANY 表將如下:

-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 操作

下麵的C代碼段顯示了我們如何能夠創造我們的COMPANY表在上麵的例子中創建表中的記錄:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s
", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("
");
   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: %s
", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully
");
   }

   /* 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: %s
", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Records created successfully
");
   }
   sqlite3_close(db);
   return 0;
}

上述程序編譯和執行時,它會創建COMPANY表中的記錄,並會顯示以下兩行:

Opened database successfully
Records created successfully

SELECT 操作

在我們開始之前獲取記錄與實際的例子,讓我給回調函數,這是我們在我們的例子中使用的一個小細節。這個回調提供了一個SELECT語句的方式獲得結果。它具有以下聲明:

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 */
);

如果上麵的回調提供sqlite_exec()程序作為第三個參數,SQLite將調用這個回調函數中處理的每個記錄在每個執行SELECT語句在SQL參數。

下麵的C代碼段,表明我們如何能夠獲取並顯示COMPANY表中在上麵的例子中創建表的記錄:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

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 = %s
", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("
");
   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: %s
", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully
");
   }

   /* 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: %s
", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully
");
   }
   sqlite3_close(db);
   return 0;
}

上述程序編譯和執行時,它會產生以下結果:

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 操作

下麵的C代碼段顯示了我們如何使用UPDATE語句來更新任何記錄,然後獲取並顯示更新的記錄,從COMPANY 表:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

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 = %s
", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("
");
   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: %s
", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully
");
   }

   /* 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: %s
", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully
");
   }
   sqlite3_close(db);
   return 0;
}

上述程序編譯和執行時,它會產生以下結果:

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

刪除操作

下麵的C代碼段顯示了我們如何使用DELETE語句刪除任何記錄,然後獲取並顯示COMPANY 表剩餘的記錄:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 

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 = %s
", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("
");
   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: %s
", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully
");
   }

   /* 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: %s
", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Operation done successfully
");
   }
   sqlite3_close(db);
   return 0;
}

上述程序編譯和執行時,它會產生以下結果:

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