sqlite3如何插入数据
时间: 2024-06-01 16:07:07 浏览: 235
sqlite3性能优化源代码 数据插入 开启事务 执行准备 性能提升 每秒百万条数据写入
5星 · 资源好评率100%
在SQLite中,可以使用sqlite3_exec()函数和sqlite3_prepare_v2()函数来插入数据。下面是一个插入数据的示例代码,其中包含两种不同的插入数据的方法:
引用:
```c
sqlite3_exec(db,"begin;",0,0,0); // 开始事务
sqlite3_stmt *stmt;
const char* sql = "insert into t1 values(?,?,?,?)"; // SQL语句
sqlite3_prepare_v2(db,sql,strlen(sql),&stmt,0);
for(int i=0;i<nCount;++i) { // 循环插入数据
sqlite3_reset(stmt);
sqlite3_bind_int(stmt,1,i);
sqlite3_bind_int(stmt,1,i*2);
sqlite3_bind_int(stmt,1,i/2);
sqlite3_bind_double(stmt,1,i*i);
}
sqlite3_finalize(stmt);
sqlite3_exec(db,"commit;",0,0,0); // 提交事务
```
引用:
```c
// 连接数据库
// 定义变量
char* zErrMsg = 0;
int rc;
sqlite3_stmt *stmt;
// 打开数据库
rc = sqlite3_open("test.db", &db);
// 创建表格
char* sql = "CREATE TABLE COMPANY(" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL );";
// 执行SQL语句
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
// 插入数据
const char* data = "Callback function called";
char *sql2 = "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 );";
// 将SQL语句编译成字节码
rc = sqlite3_prepare_v2(db, sql2, -1, &stmt, 0);
// 执行编译好的SQL语句
rc = sqlite3_step(stmt);
// 释放资源
sqlite3_finalize(stmt);
sqlite3_close(db);
```
阅读全文