VC++6.0 Sqlite3调用例子
在VC++ 6.0中调用SQLite 3的示例代码如下:
#include <iostream>
#include <sqlite3.h>
int main(int argc, char* argv[])
{
sqlite3* db;
char* errMsg = nullptr;
int rc;
// 打开数据库
rc = sqlite3_open("example.db", &db);
if (rc) {
std::cerr << "无法打开数据库: " << sqlite3_errmsg(db) << std::endl;
sqlite3_close(db);
return 1;
}
// 创建一个表
const char* createTableSQL =
"CREATE TABLE IF NOT EXISTS users ("
"id INTEGER PRIMARY KEY,"
"username TEXT,"
"email TEXT"
");";
rc = sqlite3_exec(db, createTableSQL, nullptr, nullptr, &errMsg);
if (rc != SQLITE_OK) {
std::cerr << "SQL错误: " << errMsg << std::endl;
sqlite3_free(errMsg);
}
// 插入数据
const char* insertSQL = "INSERT INTO users (username, email) VALUES ('Alice', 'alice@example.com');";
rc = sqlite3_exec(db, insertSQL, nullptr, nullptr, &errMsg);
if (rc != SQLITE_OK) {
std::cerr << "SQL错误: " << errMsg << std::endl;
sqlite3_free(errMsg);
}
// 查询数据
const char* selectSQL = "SELECT id, username, email FROM users;";
sqlite3_stmt* stmt;
rc = sqlite3_prepare_v2(db, selectSQL, -1, &stmt, nullptr);
if (rc == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
int id = sqlite3_column_int(stmt, 0);
const unsigned char* username = sqlite3_column_text(stmt, 1);
const unsigned char* email = sqlite3_column_text(stmt, 2);
std::cout << "ID: " << id << ", Username: " << username << ", Email: " << email << std::endl;
}
sqlite3_finalize(stmt);
} else {
std::cerr << "SQL错误: " << errMsg << std::endl;
sqlite3_free(errMsg);
}
// 关闭数据库
sqlite3_close(db);
return 0;
}
这段代码展示了如何在VC++ 6.0中使用SQLite 3的基本操作,包括打开数据库、创建表、插入数据、查询数据和关闭数据库。注意,这里假设SQLite 3的库文件已经被正确配置,并且example.db
数据库文件存在于程序可执行文件的相同目录下。
评论已关闭