基于C语言实现 SQL数据库和链表的相互转换

使用的函数介绍 

这里sqlite3_open、sqlite3_close就不介绍了

  1. sqlite3_prepare_v2()

    • 函数原型:int sqlite3_prepare_v2(sqlite3* db, const char* zSql, int nByte, sqlite3_stmt** ppStmt, const char** pzTail);
    • 作用:准备 SQL 语句以供执行。这个函数将 SQL 语句编译为一个预处理语句对象,并返回一个状态码以指示编译过程中的任何错误。
    • 参数解释:
      • db:指向已打开的 SQLite 数据库的指针。
      • zSql:要准备的 SQL 语句的字符串。
      • nByte:要准备的 SQL 语句的字节数,如果为负数,则直到遇到字符串的终止符(NULL 终止符)。
      • ppStmt:用于存储编译后的预处理语句对象的指针。
      • pzTail:输出参数,用于指向未使用的 SQL 语句部分的指针,通常为 NULL。
  2. sqlite3_step()

    • 函数原型:int sqlite3_step(sqlite3_stmt* pStmt);
    • 作用:执行 SQL 语句的下一个步骤。
    • 参数解释:
      • pStmt:指向预处理语句对象的指针,该对象是使用 sqlite3_prepare_v2() 编译的。
  3. sqlite3_column_int()

    • 函数原型:int sqlite3_column_int(sqlite3_stmt* pStmt, int iCol);
    • 作用:从 SQL 查询结果的当前行中获取指定整数列的值。
    • 参数解释:
      • pStmt:指向预处理语句对象的指针。
      • iCol:要获取其值的列的索引(从 0 开始)。
  4. sqlite3_column_text()

    • 函数原型:const unsigned char* sqlite3_column_text(sqlite3_stmt* pStmt, int iCol);
    • 作用:从 SQL 查询结果的当前行中获取指定文本列的值。
    • 参数解释:
      • pStmt:指向预处理语句对象的指针。
      • iCol:要获取其值的列的索引(从 0 开始)。
  5. sqlite3_finalize():
    • 函数原型:int sqlite3_finalize(sqlite3_stmt* pStmt);
    • 作用:接口中用于释放预处理语句对象(prepared statement)所占用资源的函数,可以确保资源被正确地释放,避免内存泄漏等问题。

SQLToLink()

从数据库到链表

方式一:

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

// 定义链表节点
struct Node {
    int int1;
    int int2;
    char string[100]; // 假设字符串长度最多为 100
    struct Node* next;
};

// 定义链表
struct LinkedList {
    struct Node* head;
};

// 初始化链表
void initLinkedList(struct LinkedList* list) {
    list->head = NULL;
}

// 在链表尾部添加节点
void append(struct LinkedList* list, int int1, int int2, const char* string) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        fprintf(stderr, "Memory allocation failed.\n");
        exit(1);
    }
    newNode->int1 = int1;
    newNode->int2 = int2;
    strcpy(newNode->string, string);
    newNode->next = NULL;

    if (list->head == NULL) {
        list->head = newNode;
    } else {
        struct Node* current = list->head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

int main() {
    sqlite3* db;
    sqlite3_stmt* stmt;
    int rc;

    // 打开 SQLite 数据库
    rc = sqlite3_open("your_database.db", &db);
    if (rc) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        return 1;
    }

    // 准备查询语句
    const char* sql = "SELECT * FROM your_table";
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return 1;
    }

    // 初始化链表
    struct LinkedList list;
    initLinkedList(&list);

    // 执行查询并将结果添加到链表
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        int int1 = sqlite3_column_int(stmt, 0);
        int int2 = sqlite3_column_int(stmt, 1);
        const unsigned char* string = sqlite3_column_text(stmt, 2);
        append(&list, int1, int2, (const char*)string);
    }

    // 检查查询结果
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return 1;
    }

    // 关闭数据库连接
    sqlite3_finalize(stmt);
    sqlite3_close(db);

    // 打印链表内容
    struct Node* current = list.head;
    while (current != NULL) {
        printf("%d %d %s\n", current->int1, current->int2, current->string);
        current = current->next;
    }

    // 释放链表内存
    current = list.head;
    while (current != NULL) {
        struct Node* temp = current;
        current = current->next;
        free(temp);
    }

    return 0;
}

方式二:

#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <string.h>
// 定义链表节点
struct stu{
	int id;
	char name[20];
	int score;
	struct stu *p;
};
//注意这里链表头定义的是指针类型,所以add函数的struct stu **head1应该为二级指针,
//在传递参数时应该传递链表头的地址,没有传递头指针 head 的地址。
//这意味着 add() 函数中对头指针 head 的任何修改都不会反映到 main() 函数中的头指针 head 上

struct stu *head;
// 在链表尾部添加节点
void add(struct stu **head1,int id,char *name,int score){
	struct stu *add = *head1;
	struct stu *code;
	code=(struct stu*)malloc(sizeof(struct stu));
	if(code==NULL){
		printf("error:malloc no!!!\n");
	}
	code->id=id;
	strcpy(code->name,name);
	code->score=score;
	code->p = NULL;
	if(*head1 == NULL){
		*head1=code;
	}else{
		while(add->p != NULL){
			add = add->p;
		}
		add->p = code;
	}
}
int main(int argc,char** argv)
{
	sqlite3 *pd;
	char *errmsg;
	sqlite3_stmt *ppStmt;
	// 准备查询语句
	char *sql = "select * from stu;";
	int ret = 0;
	if(argc<2){
		printf("input:%s xxx\n",argv[0]);
	}
	// 打开 SQLite 数据库
	if((ret=sqlite3_open(argv[1],&pd))!=0)
	{
		printf("ret = %d error:%s\n",ret,sqlite3_errmsg(pd));
		return -1;
	}
	if((ret = sqlite3_prepare_v2(pd,sql,-1,&ppStmt,NULL))!=0){
		printf("ret = %d error:%s\n",ret,errmsg);
		return -1;
	}
	 // 执行查询并将结果添加到链表
	while(sqlite3_step(ppStmt)==SQLITE_ROW){
		int int1 = sqlite3_column_int(ppStmt,0);

		const unsigned	char *char1 = sqlite3_column_text(ppStmt,1);

		int int2 = sqlite3_column_int(ppStmt,2);

		add(&head,int1,(char*)char1,int2);
	}
	// 打印链表内容
	struct stu *stu1 = head;
	while(stu1 != NULL){
		printf("id = %d name %s score = %d\n",\
				stu1->id,stu1->name,stu1->score);
		stu1 = stu1->p;
	}
	 // 关闭数据库连接
	sqlite3_finalize(ppStmt);
	sqlite3_close(pd);

	//释放链表内存
	while (head != NULL) {
		struct stu* temp = head;
		head = head->p;
		free(temp);
	}
	return 0;

}

LinkToSQL()

从链表到数据库

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

// 定义链表节点
struct Node {
    int int1;
    int int2;
    char string[100]; // 假设字符串长度最多为 100
    struct Node* next;
};

// 定义链表
struct LinkedList {
    struct Node* head;
};

// 初始化链表
void initLinkedList(struct LinkedList* list) {
    list->head = NULL;
}

// 在链表尾部添加节点
void append(struct LinkedList* list, int int1, int int2, const char* string) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        fprintf(stderr, "Memory allocation failed.\n");
        exit(1);
    }
    newNode->int1 = int1;
    newNode->int2 = int2;
    strcpy(newNode->string, string);
    newNode->next = NULL;

    if (list->head == NULL) {
        list->head = newNode;
    } else {
        struct Node* current = list->head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

int main() {
    sqlite3* db;
    int rc;

    // 打开 SQLite 数据库
    rc = sqlite3_open("your_database.db", &db);
    if (rc) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        return 1;
    }

    // 创建表
    const char* create_table_sql = "CREATE TABLE IF NOT EXISTS your_table (int1 INTEGER, int2 INTEGER, string TEXT);";
    rc = sqlite3_exec(db, create_table_sql, NULL, 0, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }

    // 初始化链表
    struct LinkedList list;
    initLinkedList(&list);

    // 在链表中添加一些示例数据
    append(&list, 123, 456, "Example1");
    append(&list, 789, 1011, "Example2");

    // 遍历链表并将数据插入数据库
    struct Node* current = list.head;
    while (current != NULL) {
        // 准备插入语句
        char insert_sql[200];
        sprintf(insert_sql, "INSERT INTO your_table (int1, int2, string) VALUES (%d, %d, '%s');", current->int1, current->int2, current->string);
        
        // 执行插入语句
        rc = sqlite3_exec(db, insert_sql, NULL, 0, NULL);
        if (rc != SQLITE_OK) {
            fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
            sqlite3_close(db);
            return 1;
        }

        current = current->next;
    }

    // 关闭数据库连接
    sqlite3_close(db);

    return 0;
}

相关推荐

  1. 基于C语言实现 SQL数据库相互转换

    2024-04-06 16:36:05       30 阅读
  2. 基于通讯录C语言实现

    2024-04-06 16:36:05       45 阅读
  3. 基于双向通讯录C语言实现

    2024-04-06 16:36:05       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-06 16:36:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-06 16:36:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-06 16:36:05       82 阅读
  4. Python语言-面向对象

    2024-04-06 16:36:05       91 阅读

热门阅读

  1. 使用 PyArmor 加密一个 Python 包

    2024-04-06 16:36:05       39 阅读
  2. Ubuntu系统下安装SQLite Browser教程

    2024-04-06 16:36:05       32 阅读
  3. 【Python全栈】Python实现交通信号灯

    2024-04-06 16:36:05       40 阅读
  4. ES6的new Set()方法有什么用法

    2024-04-06 16:36:05       34 阅读
  5. LeetCode 1365. 有多少小于当前数字的数字

    2024-04-06 16:36:05       40 阅读
  6. 位运算-力扣67. 二进制求和

    2024-04-06 16:36:05       35 阅读
  7. Linux查看日志的几种方法

    2024-04-06 16:36:05       30 阅读
  8. Python数据分析十六

    2024-04-06 16:36:05       38 阅读