基于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;
}

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于C语言实现完整的双链表的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 双链表节点结构体 typedef struct Node { int data; // 数据 struct Node* prev; // 指向前一个节点的指针 struct Node* next; // 指向后一个节点的指针 } Node; // 创建新节点 Node* createNode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->prev = NULL; newNode->next = NULL; return newNode; } // 在双链表末尾插入节点 void insertAtEnd(Node** head, int data) { Node* newNode = createNode(data); if (*head == NULL) { *head = newNode; } else { Node* temp = *head; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; newNode->prev = temp; } } // 在双链表开头插入节点 void insertAtBeginning(Node** head, int data) { Node* newNode = createNode(data); if (*head == NULL) { *head = newNode; } else { (*head)->prev = newNode; newNode->next = *head; *head = newNode; } } // 在指定位置插入节点 void insertAtPosition(Node** head, int data, int position) { if (position <= 0) { printf("Invalid position!\n"); return; } if (position == 1) { insertAtBeginning(head, data); return; } Node* newNode = createNode(data); Node* temp = *head; int count = 1; while (temp != NULL && count < position) { temp = temp->next; count++; } if (temp == NULL && count < position) { printf("Invalid position!\n"); return; } newNode->prev = temp->prev; newNode->next = temp; if (temp->prev != NULL) { temp->prev->next = newNode; } temp->prev = newNode; } // 删除指定位置的节点 void deleteAtPosition(Node** head, int position) { if (*head == NULL) { printf("List is empty!\n"); return; } if (position <= 0) { printf("Invalid position!\n"); return; } Node* temp = *head; int count = 1; while (temp != NULL && count < position) { temp = temp->next; count++; } if (temp == NULL && count < position) { printf("Invalid position!\n"); return; } if (temp->prev != NULL) { temp->prev->next = temp->next; } else { *head = temp->next; } if (temp->next != NULL) { temp->next->prev = temp->prev; } free(temp); } // 打印双链表 void printList(Node* node) { printf("List: "); while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n"); } // 测试 int main() { Node* head = NULL; insertAtEnd(&head, 1); insertAtEnd(&head, 2); insertAtEnd(&head, 3); printList(head); insertAtBeginning(&head, 0); printList(head); insertAtPosition(&head, 4, 5); insertAtPosition(&head, 4, 3); printList(head); deleteAtPosition(&head, 2); printList(head); return 0; } ``` 这段代码实现了双链表的基本操作,包括在末尾插入节点、在开头插入节点、在指定位置插入节点、删除指定位置的节点以及打印链表。你可以根据自己的需求进行调整和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值