MySQL BLOB 记录的读写, MySQL 5.0.91, WIN11, VS2022
作者:互联网
1. VS2022 控制台工程,Debug X86模式,字符集选用Multi-Byte
2. 把MySQL的头文件和库文件路径加进工程。
3. 把MySQL的库目录中的动态链接库libmysql.dll 复制到工程的当前工作目录下
4. 创建表,data 字段是blob 类型,
5. 定义一段数据 100个字节, 0x55,0xaa开头, 0x55,0xaa结尾。
6. 把数据插入数据库。
7. 读出数据,打印头尾的数据验证结果。
程序运行效果:
程序 MySQLTest2.cpp
// MySQLTest2.cpp : This file contains the 'main' function. Program execution begins and ends there. // C读写MySQL BLOB数据 // XGZ 2022-07-16 SZ #include <WinSock2.h> #include <mysql.h>
#include <stdio.h>
#pragma comment(lib,"libmysql.lib") int main() { MYSQL* conn; MYSQL_ROW row; MYSQL_RES* res; int nrow; int ncolum; conn = mysql_init(NULL); if (!conn) { printf("\n <ERR> mysql_init failed!"); return -1; } //本地连接到test数据库 conn = mysql_real_connect(conn, "127.0.0.1", "root", "root", "test", 0, NULL, 0); if (conn) { printf("\n<OK>mysql_real_connect success!"); } else { printf("\n<ERR>mysql_real_connect failed!"); return -1; } //创建表 if (mysql_query(conn, "create table testb (name varchar(256), data blob, size int);") != 0) { printf("\n Create failed"); return -1; } //插入数据 0================================ MYSQL_STMT* stmt = mysql_stmt_init(conn); MYSQL_BIND bind[3] ={0}; char value[100]; char name[256]; int length; strcpy_s(name, 256, "name123"); memset(value, 0, 100); value[0] = 0x55; value[1] = 0xaa; value[98] = 0x55; value[99] = 0xaa; length = 100; if (!stmt) return -1; char sql2[1024] = "insert into testb (name,data,size) values(?,?,?);"; if (mysql_stmt_prepare(stmt, sql2, strlen(sql2))) return -1; bind[0].buffer_type = MYSQL_TYPE_STRING; bind[0].buffer = name; bind[0].buffer_length = strlen(name); bind[1].buffer_type = MYSQL_TYPE_BLOB; bind[1].buffer = value; bind[1].buffer_length = length; bind[2].buffer_type = MYSQL_TYPE_LONG; bind[2].buffer = &length; if (mysql_stmt_bind_param(stmt, bind) != 0) return -1; if (mysql_stmt_execute(stmt) != 0) return -1; mysql_stmt_close(stmt); //=============================== //查询test数据库user表 mysql_query(conn, "select * from testb"); res = mysql_store_result(conn); if (NULL == res) { return 0; } ncolum = mysql_num_fields(res); nrow = mysql_num_rows(res); printf("\nncolum=%d,count=%d", ncolum, nrow); //读取并打印数据 while (row = mysql_fetch_row(res)) { printf("\n name= %s", row[0]); printf("\n data = %2X,%2X,%2X ....%2X,%2X,%2X", row[1][0], row[1][1], row[1][2], row[1][97], row[1][98], row[1][99] ); printf("\n size = %d", atoi(row[2])); } mysql_close(conn); return 0; }
标签:5.0,return,bind,MySQL,stmt,BLOB,mysql,conn,row 来源: https://www.cnblogs.com/xgz21/p/16484387.html