• 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;
    }
  • 相关阅读:
    Linq查询操作之排序操作
    记一次docker机器无法访问本身的端口的错误2020-06-17
    prometheus监控docker的状态2020-06-17
    Docker RabbitMQ 重新启动时遇到错误
    Docker-Compose的地址与公司网络冲突
    MongDB自动运行脚本
    RabbitMQ内存泄露问题
    离线安装K3S Server(v1.17.4+k3s1)
    kubernetes yaml文件学习
    Docker Desktop启动Kubernetes
  • 原文地址:https://www.cnblogs.com/tsfh/p/8877495.html
Copyright © 2020-2023  润新知