在C++中使用SQLite需要使用SQLite C/C++ API來進行數據庫操作。下面是一個簡單的示例來演示如何在C++中使用SQLite:
#include <sqlite3.h>
#include <iostream>
int main() {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if(rc) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return(0);
} else {
std::cout << "Opened database successfully" << std::endl;
}
// 創建表
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, 0, 0, &zErrMsg);
if(rc != SQLITE_OK) {
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
} else {
std::cout << "Table created successfully" << std::endl;
}
sqlite3_close(db);
return 0;
}
以上示例代碼演示了如何在C++中使用SQLite創建一個數據庫并創建一個名為COMPANY
的表。在實際的應用中,您可以使用SQLite API進行更多的數據庫操作,如插入數據、查詢數據等。更多SQLite C/C++ API的用法可以參考SQLite官方文檔。