在C++中使用SQLite3數(shù)據(jù)庫(kù)時(shí),需要包含SQLite3的頭文件,并使用SQLite3的API進(jìn)行數(shù)據(jù)庫(kù)操作。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用SQLite3在C++中創(chuàng)建數(shù)據(jù)庫(kù)、創(chuàng)建表、插入數(shù)據(jù)、查詢數(shù)據(jù)等操作:
#include <iostream>
#include <sqlite3.h>
int main() {
sqlite3* db;
char* errorMessage;
// 打開(kāi)數(shù)據(jù)庫(kù)
int rc = sqlite3_open("test.db", &db);
if (rc) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return 1;
} else {
std::cout << "Opened database successfully" << std::endl;
}
// 創(chuàng)建表
const char* sql = "CREATE TABLE COMPANY("
"ID INT PRIMARY KEY NOT NULL,"
"NAME TEXT NOT NULL,"
"AGE INT NOT NULL,"
"ADDRESS CHAR(50),"
"SALARY REAL );";
rc = sqlite3_exec(db, sql, NULL, 0, &errorMessage);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
} else {
std::cout << "Table created successfully" << std::endl;
}
// 插入數(shù)據(jù)
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
"VALUES (1, 'Paul', 32, 'California', 20000.00);";
rc = sqlite3_exec(db, sql, NULL, 0, &errorMessage);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
} else {
std::cout << "Record inserted successfully" << std::endl;
}
// 查詢數(shù)據(jù)
sql = "SELECT * FROM COMPANY;";
rc = sqlite3_exec(db, sql, callback, 0, &errorMessage);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
}
// 關(guān)閉數(shù)據(jù)庫(kù)
sqlite3_close(db);
return 0;
}
在上面的示例中,我們首先使用sqlite3_open
函數(shù)打開(kāi)一個(gè)名為test.db
的數(shù)據(jù)庫(kù),然后使用sqlite3_exec
函數(shù)執(zhí)行SQL語(yǔ)句來(lái)創(chuàng)建表、插入數(shù)據(jù)和查詢數(shù)據(jù)。需要注意的是,sqlite3_exec
函數(shù)的第三個(gè)參數(shù)是一個(gè)回調(diào)函數(shù),用來(lái)處理查詢結(jié)果。在實(shí)際使用中,需要根據(jù)具體需求來(lái)調(diào)整和完善代碼。