使用C++编写一个sqlite使用预编译的例子
时间: 2023-06-25 14:05:36 浏览: 52
以下是使用C++编写的SQLite使用预编译的例子:
```c++
#include <sqlite3.h>
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int main(){
sqlite3 *db;
sqlite3_stmt *stmt;
int rc;
char *zErrMsg = 0;
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return 0;
}
const char *sql = "INSERT INTO test_table (id, name, age) VALUES (?, ?, ?)";
rc = sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
return 0;
}
int id = 1;
const char* name = "Tom";
int age = 20;
sqlite3_bind_int(stmt, 1, id);
sqlite3_bind_text(stmt, 2, name, strlen(name), NULL);
sqlite3_bind_int(stmt, 3, age);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
return 0;
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return 0;
}
```
该示例使用了SQLite的C语言接口,其中使用了sqlite3_prepare_v2函数对SQL语句进行预编译,然后使用sqlite3_bind_xxx函数对预编译语句中的占位符进行绑定,最后使用sqlite3_step函数执行预编译语句。执行完毕后,使用sqlite3_finalize函数对预编译语句进行清理,最后使用sqlite3_close函数关闭数据库连接。