您的位置:首页 > 编程语言 > C语言/C++

c/vc/c++ 将mysql二进制字段(longblob类型)读出来保存成文件

2012-03-16 13:41 633 查看
最后的写文件操作,用的是cfile,记得选择要支持mfc

#include "StdAfx.h"

#include <afxwin.h>

#include <stdio.h>

#include "winsock2.h"

#pragma comment(lib,"ws2_32")

#include <mysql.h>

#include <assert.h>

#include <string.h>

#include <stdlib.h>

#include "mysql.h"

#include "stdio.h"

#include "io.h"

#include "sys/stat.h"

#include <FCNTL.H>

#include<stdlib.h>

#pragma comment(lib,"libmySQL.lib")

#pragma comment(lib,"ws2_32")

void test_write(MYSQL& client)

{

MYSQL_STMT* stmt = mysql_stmt_init(&client);

assert(NULL!=stmt);

const char* sql = "select file from tablename2";

int sql_len = strlen(sql);

int ret = mysql_stmt_prepare(stmt, sql, sql_len);

assert(0==ret);

// ERR_LOG("param count:%d", (int)mysql_stmt_param_count(stmt));

//

MYSQL_BIND result = {0};

unsigned long total_length = 0;

result.buffer_type = MYSQL_TYPE_LONG_BLOB;

result.length = &total_length;

ret = mysql_stmt_bind_result(stmt, &result);

assert(0==ret);

ret = mysql_stmt_execute(stmt);

assert(0==ret);

ret = mysql_stmt_store_result(stmt);

assert(0==ret);

//while (mysql_stmt_fetch(stmt)!=0)

for (;;)

{

ret = mysql_stmt_fetch(stmt);

if (ret!=0 && ret!=MYSQL_DATA_TRUNCATED) break;

int start = 0;

char *buf=new char[total_length];

memset(buf,0,sizeof(buf));

printf("total_length=%lu\n", total_length);

while (start<(int)total_length)

{

result.buffer = (buf+start);

result.buffer_length = 3; //每次读这么长

ret = mysql_stmt_fetch_column(stmt, &result, 0, start);

if (ret!=0)

{

return;

}

start += result.buffer_length;

}

CFile f;

if(f.Open("e:\\aaa.7z", CFile::modeCreate|CFile::modeWrite | CFile::typeBinary))

{

f.WriteHuge(buf,total_length);

f.Close();

}

}

mysql_stmt_close(stmt);

}

int main(int argc, char* argv[])

{

MYSQL client;

mysql_init(&client);

if ((mysql_real_connect(&client, "192.168.1.101", "root", "", "test", 0, NULL, 0)) == NULL) {

printf("connect mysql, %sn", mysql_error(&client));

return 1;

}

test_write(client);

//ERR_LOG("OK");

return ;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: