SQLite – C/C++

2022-08-17 09:59 更新

安裝

在 C/C++ 程序中使用 SQLite 之前,我們需要確保機器上已經有 SQLite 庫??梢圆榭?SQLite 安裝章節(jié)了解安裝過程。

C/C++ 接口 API

以下是重要的 C&C++ / SQLite 接口程序,可以滿足您在 C/C++ 程序中使用 SQLite 數據庫的需求。如果您需要了解更多細節(jié),請查看 SQLite 官方文檔。

序號 API & 描述
1 sqlite3_open(const char *filename, sqlite3 **ppDb)

該例程打開一個指向 SQLite 數據庫文件的連接,返回一個用于其他 SQLite 程序的數據庫連接對象。

如果 filename 參數是 NULL 或 ':memory:',那么 sqlite3_open() 將會在 RAM 中創(chuàng)建一個內存數據庫,這只會在 session 的有效時間內持續(xù)。

如果文件名 filename 不為 NULL,那么 sqlite3_open() 將使用這個參數值嘗試打開數據庫文件。如果該名稱的文件不存在,sqlite3_open() 將創(chuàng)建一個新的命名為該名稱的數據庫文件并打開。

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

該例程提供了一個執(zhí)行 SQL 命令的快捷方式,SQL 命令由 sql 參數提供,可以由多個 SQL 命令組成。

在這里,第一個參數 sqlite3 是打開的數據庫對象,sqlite_callback 是一個回調,data 作為其第一個參數,errmsg 將被返回用來獲取程序生成的任何錯誤。

sqlite3_exec() 程序解析并執(zhí)行由 sql 參數所給的每個命令,直到字符串結束或者遇到錯誤為止。

3 sqlite3_close(sqlite3*)

該例程關閉之前調用 sqlite3_open() 打開的數據庫連接。所有與連接相關的語句都應在連接關閉之前完成。

如果還有查詢沒有完成,sqlite3_close() 將返回 SQLITE_BUSY 禁止關閉的錯誤消息。

連接數據庫

下面的 C 代碼段顯示了如何連接到一個現有的數據庫。如果數據庫不存在,那么它就會被創(chuàng)建,最后將返回一個數據庫對象。

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

現在,讓我們來編譯和運行上面的程序,在當前目錄中創(chuàng)建我們的數據庫 test.db。您可以根據需要改變路徑。

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

如果要使用 C++ 源代碼,可以按照下列所示編譯代碼:

$g++ test.c -l sqlite3

在這里,把我們的程序鏈接上 sqlite3 庫,以便向 C 程序提供必要的函數。這將在您的目錄下創(chuàng)建一個數據庫文件 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

創(chuàng)建表

下面的 C 代碼段將用于在先前創(chuàng)建的數據庫中創(chuàng)建一個表:

#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&lt;argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "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: %s\n", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stdout, "Opened database successfully\n");
   }

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

上述程序編譯和執(zhí)行時,它會在 test.db 文件中創(chuàng)建 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 代碼段顯示了如何在上面創(chuàng)建的 COMPANY 表中創(chuàng)建記錄:

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

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

上述程序編譯和執(zhí)行時,它會在 COMPANY 表中創(chuàng)建給定記錄,并會顯示以下兩行:

Opened database successfully
Records created successfully

SELECT 操作

在我們開始講解獲取記錄的實例之前,讓我們先了解下回調函數的一些細節(jié),這將在我們的實例使用到。這個回調提供了一個從 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 將為 SQL 參數內執(zhí)行的每個 SELECT 語句中處理的每個記錄調用這個回調函數。

下面的 C 代碼段顯示了如何從前面創(chuàng)建的 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&lt;argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "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: %s\n", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
   }

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

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

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

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

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

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

下面的 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\n", azColName[i], argv[i] ? argv[i] : "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: %s\n", sqlite3_errmsg(db));
        exit(0);
    }
    else
    {
        fprintf(stderr, "Opened database successfully\n");
    }                                                                   /* 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\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }
    else
    {
        fprintf(stdout, "Operation done successfully\n");
    }
    sqlite3_close(db);
    return 0;
}

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

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


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號