C++写sqlite3
时间: 2023-09-26 19:11:14 浏览: 88
我很乐意回答您的问题。下面是一个简单的SQLite3示例程序,它展示了如何在C语言中使用SQLite3库进行数据库操作:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
// 回调函数
static int callback(void *data, int argc, char **argv, char **azColName)
{
int i;
for(i = 0; i < argc; i++)
{
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char *argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
const char *sql;
// 打开数据库
rc = sqlite3_open("test.db", &db);
if(rc)
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
// 创建表
sql = "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, callback, 0, &zErrMsg);
if(rc != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else
{
fprintf(stdout, "Table created successfully\n");
}
// 插入数据
sql = "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, callback, 0, &zErrMsg);
if(rc != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else
{
fprintf(stdout, "Records created successfully\n");
}
// 查询数据
sql = "SELECT * from COMPANY";
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if(rc != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else
{
fprintf(stdout, "Operation done successfully\n");
}
// 关闭数据库
sqlite3_close(db);
return 0;
}
```
以上示例程序将创建名为"test.db"的SQLite3数据库,并在其中创建一个名为"COMPANY"的表。然后,它会向表中插入一些数据,并查询该表以显示结果。为了运行此程序,您将需要安装SQLite3库并编译上述代码。
阅读全文