1. 程式人生 > >c/vc/c++ 將mysql二進位制欄位(longblob型別)讀出來儲存成檔案

c/vc/c++ 將mysql二進位制欄位(longblob型別)讀出來儲存成檔案

最後的寫檔案操作,用的是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 ;
 
}