#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "sqlite3.h"
// 回调函数
int huidiao(void *data, int col, char **val, char **name){
static int row = 0;
printf("\nrow : %d\n",++row);
// 这里可以对每一行数据进行处理
for(int i = 0; i < col; i++){
printf("%s = %s\n", name[i], val[i] ? val[i] : "NULL");
}
return SQLITE_OK;
}
int main(int argc, char* argv[]){
sqlite3 *db;
// 给回调1用的参数
char *err_msg = 0;
int huidiao_arg=33;
// 给getTable用的参数
char **table;
int row, col;
char *errmsg = 0;
// 打开database
int rc = sqlite3_open("stu.db", &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
// 定义SQL语句
char *sql = "SELECT * FROM t2";
// 执行sql语句方式1: 如果把回调和回调参数都设置为NULL,那么就是执行sql,不需要返回数据
rc = sqlite3_exec(db, sql, huidiao, &huidiao_arg, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
// 执行sql语句方式2:使用 **result 接收
rc = sqlite3_get_table(db, sql, &table, &row, &col, &errmsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
return 1;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%s\t", table[i * col + j]);
}
printf("\n");
}
sqlite3_free_table(table);
// 关闭database
sqlite3_close(db);
return 0;
}
/* 执行示例:
D:\gopath1.18\src\gitee.com\wangwei830\cGBase8s\SQLITE>a.exe
row : 1
id = 1
name = aaa
date = 2024-01-14
time = 01:45:34
row : 2
id = 2
name = bbb
date = 2024-01-14
time = 01:46:14
row : 3
id = 3
name = ccc
date = 2024-01-14
time = 01:46:25
id name date time
1 aaa 2024-01-14 01:45:34
2 bbb 2024-01-14 01:46:14
D:\gopath1.18\src\gitee.com\wangwei830\cGBase8s\SQLITE>
*/
/* 资源下载:
#windows 二进制
wget https://www.sqlite.org/2023/sqlite-dll-win-x86-3440200.zip
wget https://www.sqlite.org/2023/sqlite-dll-win-x64-3440200.zip
#windows 客户端
wget https://www.sqlite.org/2023/sqlite-tools-win-x64-3440200.zip
#linux 64位
wget https://www.sqlite.org/2023/sqlite-tools-linux-x64-3440200.zip
#源代码
wget https://www.sqlite.org/2023/sqlite-amalgamation-3440200.zip
#文档
wget https://www.sqlite.org/2023/sqlite-doc-3440200.zip
#说明:
#下载完了,然后解压,把sqlite3.h和sqlite3.cpp复制到vs2022的项目中,然后就可以使用了。
#软件存储再D:/2024目录下了。
#SQLITE 下载地址: http://www.sqlite.org/download.html
*/
/* Mackfile 方式编译
OBJ += main.o
OBJ += sqlite3.o
FLAGS = -Wall
CC = gcc
CFLAGS = -g $(FLAGS)
main: $(OBJ)
$(CC) $(OBJ) -o $@ $(FLAGS) -lpthread -ldl
%.o: %.c
$(CC) -c $^ -o $@ $(FLAGS)
clean:
rm $(OBJ) main -rfv
*/
C语言面对Sqlite数据库编程
最新推荐文章于 2025-04-24 17:09:53 发布