zoukankan      html  css  js  c++  java
  • c/c++ 获取mysql数据库以blob类型储存的图片

    简单的code如下:

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <cstring>
    #include <mysql/mysql.h>
    using namespace std;
    
    int main()
    {
        const char username[] = "username";
        const char password[] = "password";
        const char host[]   = "192.168.0.100";
        const char dbname[] = "dbname";
    
        MYSQL conn;
        if(NULL == mysql_init(&conn))
        {
            cerr << "init conn fail." << endl;
            exit(-1);
        }
    
        if (NULL == mysql_real_connect(&conn, host, username, password, dbname, 0, NULL, 0))
        {
            cerr << "connect to database error" << endl;
            exit(-1);
        }
    
        char sql[] = "select octet_length(picture), picture from tablename";
        if (0 != mysql_real_query(&conn, sql, strlen(sql)))
        {
            cerr << "query error." << endl;
            exit(-1);
        }
    
        MYSQL_RES * result = NULL;
        result = mysql_store_result(&conn);
        if (NULL == result)
        {
            cerr << "store result error." << endl;
            exit(-1);
        }
    
        if (0 >= mysql_affected_rows(&conn))
        {
            cerr << "no data be found." << endl;
            exit(-1);
        }
    
        int count = 0;
        string path = "/home/tsfh/pictures/";
        MYSQL_ROW row_record;
        while (row_record = mysql_fetch_row(result))
        {
            unsigned int size = 0;
            char * temp_buff = NULL;
    
            sscanf(row_record[0], "%d", &size);
            if(0 == size )
            {
                cerr << "invalid record!" << endl;
                continue;
            }
    
            temp_buff = (char *)malloc(size * sizeof(char) + 1);
            if(NULL == temp_buff)
            {
                cerr << "malloc error!" <<endl;
                exit(1);
            }
            memset(temp_buff, 0, size * sizeof(char) + 1);
            memcpy(temp_buff, row_record[1], size * sizeof(char));
    
            stringstream pic_name;
            pic_name << count << ".jpg";
            ofstream outfile(path + pic_name.str(), ios::binary);
            outfile.write(temp_buff, size);
    
            count++;
            free(temp_buff);
        }
    
        mysql_close(&conn);
        return 0;
    }
  • 相关阅读:
    20170620_javaweb_小结
    win7电脑关机时间长怎么办
    hadoop环境搭建之关于NAT模式静态IP的设置 ---VMware12+CentOs7
    初识bigdata时的一些技能小贴士
    mysql 免安装版 + sqlyog 安装 步骤 --- 发的有点晚
    Python开发之IDE选择
    Python解释器换源
    Anaconda安装与使用
    安装Python环境
    Python和其他编程语言
  • 原文地址:https://www.cnblogs.com/tsfh/p/8877495.html
Copyright © 2011-2022 走看看