C++使用sqlite3创建数据库,并实现增、删、查、改的代码
时间: 2023-07-10 11:03:59 浏览: 88
以下是使用C++语言和sqlite3库来创建数据库,并实现增、删、查、改的代码示例:
首先,需要包含sqlite3.h头文件和iostream头文件
```c++
#include <sqlite3.h>
#include <iostream>
```
接着,定义一个回调函数,用于处理查询结果:
```c++
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
std::cout << azColName[i] << " = " << (argv[i] ? argv[i] : "NULL") << std::endl;
}
std::cout << std::endl;
return 0;
}
```
然后,在主函数中创建或打开数据库,并执行增、删、查、改操作:
```c++
int main(int argc, char* argv[]){
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::cerr << "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, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
}else{
std::cerr << "Table created successfully" << std::endl;
}
// 插入数据
const char* sql_insert_data = "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_data, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
}else{
std::cerr << "Records created successfully" << std::endl;
}
// 查询数据
const char* sql_select_data = "SELECT * from COMPANY";
rc = sqlite3_exec(db, sql_select_data, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
}else{
std::cerr << "Operation done successfully" << std::endl;
}
// 更新数据
const char* sql_update_data = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; "
"SELECT * from COMPANY";
rc = sqlite3_exec(db, sql_update_data, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
}else{
std::cerr << "Total updated: " << sqlite3_changes(db) << std::endl;
}
// 删除数据
const char* sql_delete_data = "DELETE from COMPANY where ID=2; "
"SELECT * from COMPANY";
rc = sqlite3_exec(db, sql_delete_data, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
std::cerr << "SQL error: " << zErrMsg << std::endl;
sqlite3_free(zErrMsg);
}else{
std::cerr << "Total deleted: " << sqlite3_changes(db) << std::endl;
}
sqlite3_close(db);
return 0;
}
```
上述代码创建了一个名为“test.db”的数据库,并在其中创建名为“COMPANY”的表。接着,插入了几条记录,并查询了所有记录。然后,更新了一条记录,并查询了所有记录。最后,删除了一条记录,并查询了所有记录。
注意:以上代码仅为示例,实际应用中需要根据具体情况进行修改。
阅读全文