SQLite C++ Tutorial: Usage Guide
To use SQLite in C++, one must utilize the SQLite C/C++ API for database operations. Below is a simple example demonstrating how to use SQLite in C++.
#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;
}
The example code above demonstrates how to use SQLite in C++ to create a database and a table named COMPANY. In real applications, you can use the SQLite API for more database operations such as inserting data, querying data, and so on. For further information, you can refer to the official SQLite documentation for usage of the SQLite C/C++ API.