C++利用Sqlite3实现增删改查等功能
时间: 2023-11-22 19:56:32 浏览: 138
使用SQLite3实现增删改查等功能需要先安装SQLite3的库文件和头文件,然后在C++代码中调用SQLite3提供的API来实现相应的功能。
以下是一个简单的示例,演示如何使用SQLite3在C++中实现增删改查等功能:
```cpp
#include <iostream>
#include <sqlite3.h>
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 1;
} else {
std::cout << "Opened database successfully" << std::endl;
}
// 创建表
const char *sql_create_table = "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_create_table, 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;
}
// 插入数据
const char *sql_insert = "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 );";
rc = sqlite3_exec(db, sql_insert, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
} else {
std::cout << "Records created successfully" << std::endl;
}
// 查询数据
const char *sql_select = "SELECT * from COMPANY";
sqlite3_stmt *stmt;
rc = sqlite3_prepare_v2(db, sql_select, -1, &stmt, nullptr);
if (rc == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
int id = sqlite3_column_int(stmt, 0);
const unsigned char *name = sqlite3_column_text(stmt, 1);
int age = sqlite3_column_int(stmt, 2);
const unsigned char *address = sqlite3_column_text(stmt, 3);
double salary = sqlite3_column_double(stmt, 4);
std::cout << "ID = " << id << ", NAME = " << name << ", AGE = " << age <<
", ADDRESS = " << address << ", SALARY = " << salary << std::endl;
}
sqlite3_finalize(stmt);
} else {
std::cerr << "SQL error: " << sqlite3_errmsg(db) << std::endl;
}
// 更新数据
const char *sql_update = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
rc = sqlite3_exec(db, sql_update, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
} else {
std::cout << "Records updated successfully" << std::endl;
}
// 删除数据
const char *sql_delete = "DELETE from COMPANY where ID=2;";
rc = sqlite3_exec(db, sql_delete, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
} else {
std::cout << "Records deleted successfully" << std::endl;
}
sqlite3_close(db);
return 0;
}
```
在这个示例中,我们首先打开一个名为“test.db”的数据库,然后创建了一个名为“COMPANY”的表,并向表中插入了一些数据。接着,我们查询了表中的数据,并尝试更新和删除数据。
当然,这只是一个简单的示例,实际使用中还需要根据具体需求进行更多的操作。但是这个示例应该足以帮助你理解如何使用SQLite3在C++中实现增删改查等功能。
阅读全文