c++连接sqlite数据库
时间: 2023-11-18 07:48:24 浏览: 36
在 C 语言中连接 SQLite 数据库,需要使用 SQLite 提供的 C API。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
int main(int argc, char* argv[])
{
sqlite3* db;
char* errmsg;
int rc;
// 打开数据库
rc = sqlite3_open("test.db", &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
// 执行 SQL 语句
rc = sqlite3_exec(db, "CREATE TABLE students (id INT, name TEXT)", NULL, NULL, &errmsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
return 1;
}
// 关闭数据库
sqlite3_close(db);
return 0;
}
```
该示例代码中:
1. `sqlite3_open()` 函数用于打开 SQLite 数据库,第一个参数是数据库文件名,第二个参数是指向 sqlite3 结构体指针的指针。
2. `sqlite3_exec()` 函数用于执行 SQL 语句,第一个参数是已打开的数据库,第二个参数是要执行的 SQL 语句,第三个和第四个参数分别是回调函数和回调函数参数,如果不需要可以传入 NULL,最后一个参数是指向错误信息的指针。
3. `sqlite3_close()` 函数用于关闭数据库连接。
需要注意的是,在实际开发中,应该对每个 SQLite API 的返回值进行错误处理,以保证程序的稳定性。