c++将图片以二进制形式存入mysql

数据库设置:

用mediumBlob 是由于在mysql中 : MYSQL 有四种类型的来存储文件,其区别就在于存储文件的大小 TinyBlob :255,BLOB :65k ,MediumBlob : 16M,Longlob : 4G。 这样可以存储多的文件。但是仅这样还不够,因为mysql默认的存储比较小,需要修改max_allowed_packet的值,修改方法如下:

                mysql>show variables like 'max_allowed_packet';

                出现了默认值为1048576 可能会有不同的,但是通常会小

修改: mysql > SET @@global.max_allowed_packet = 16777216; 设置为16M。

#include <zlib.h>
#include<stdio.h>
#include <string.h>
#include "mmysql.h"
#include <sys/stat.h>
#include<sys/types.h>

#include <string>
int get_file_size(char *path, off_t *size) {
    struct stat file_stats;
    if (stat(path, &file_stats))
        return -1;
    *size = file_stats.st_size;
    return 0;
}

int main() {
    char *filename;
    off_t size;
    filename = (char*)"png_2.png";
    if ((get_file_size(filename, &size)) == -1) {
        perror("get file size");
        return 1;
    }
    char *sql;
    //char *end;
    char *buf;
    FILE *fp;
    int n = 0;
    if ((buf = (char *) malloc(sizeof(char) * (size + 1))) == NULL) {
        perror("malloc buf");
        return 1;
    }
    if ((fp = fopen(filename, "rb")) == NULL) {
        perror("fopen file");
        return 1;
    }
    if ((n = fread(buf, 1, size, fp)) < 0) { //n=*size
        perror("fread file");
        return 1;
    }
    sql = (char *) malloc(sizeof(char) * n * 2 + 256); //2n+1+strlen(other sql)
    if (sql == NULL) {
        perror("malloc sql");
        return 1;
    }
    mmysql *pInstall = mmysql::makeInstall();
    pInstall->mysql_connect("root", "nyy123456", "uwb");
    char * b_s;
    b_s=pInstall->ConvertBinaryToString( buf, n);
    char mysql[] = "insert into uwb_map (id, map_name, map_data) values(null, 'peter','%s')";
    sprintf(sql, mysql,b_s);
    pInstall->mysql_insert(sql, strlen(sql));
    return 1;
}

/*************************************************************************
 > File Name: mysql.cpp
 > Author: mouse
 > Mail: [email protected]
 > Created Time: Tue 07 Nov 2017 04:19:27 PM CST
 ************************************************************************/

#include "mmysql.h"
#include <iostream>
#include <cstring>
#include<string>
#include <sstream>
//#include </usr/include/mysql/mysql.h>
#include <mysql/mysql.h>
using namespace std;
mmysql* mmysql::pInstall = new mmysql();
mmysql::mmysql() {
    this->dbHandle = mysql_init(NULL);
}
mmysql::~mmysql() {
    mysql_close(this->dbHandle);
}

mmysql* mmysql::makeInstall() {
    return pInstall;
}

void mmysql::mysql_connect(const char* user, const char* passwd,
        const char* dbname) {
    if (mysql_real_connect(this->dbHandle, "localhost", user, passwd, dbname, 0,
    NULL, 0)) {
        cout << "连接成功" << endl;
        // 设置编码
        mysql_query(dbHandle, "set names utf8");
    } else {
        this->erron = 1;
    }
}
float mmysql::float_to_float(float f, int bits) {
    stringstream ss;
    ss << fixed << setprecision(bits) << f;
    ss >> f;

    return f;
}
int mmysql::mysql_querys2(const char* query){
      if (mysql_real_query(this->dbHandle, query, strlen(query))) {
        this->erron = 2;
    } else {
                MYSQL_RES *result = mysql_store_result(this->dbHandle);
        if (result) {
            for (int i = 0; i < mysql_num_rows(result); i++) {
                MYSQL_ROW row = mysql_fetch_row(result);
                for (int j = 0; j < mysql_num_fields(result); j++) {
                    //printf("%s\t", row[j]);
                    cout << "--" <<  row[j]<<endl;
                }
                cout << "\n"<<endl;
            }
            }
        
        mysql_free_result(result);
                }        
}
int mmysql::mysql_querys(const char* query, unsigned char * cValue) {
    int n=0;
    float xyz[6000];
    if (mysql_real_query(this->dbHandle, query, strlen(query))) {
        this->erron = 2;
    } else {
        MYSQL_RES *result = mysql_store_result(this->dbHandle);
        if (result) {
            for (int i = 0; i < mysql_num_rows(result); i++) {
                MYSQL_ROW row = mysql_fetch_row(result);
                for (int j = 0; j < mysql_num_fields(result); j++) {
                    if (j == 2 || j == 3 || j == 4) {
                        float f = atof(row[j]);
                        xyz[n] = float_to_float(f, 2);
                        n=n+1;
                    }
                    //printf("%s\t", row[j]);
                }
                //printf("\n");
            }
                        printf("---所有的浮点数个数: %d---------- \n", n);
              for (int m = 0; m < n; m++) {
                  unsigned char *fValue = (unsigned char *) &xyz[m];
                  for(int i=0;i<4;i++){
                     memcpy(cValue + m*4+i, &fValue[i], 1);
                  }
            }
        }
        mysql_free_result(result);
    }
      return n*4;
}
void mmysql::mysql_insert(const char *cmd,unsigned int l) {
    cout << "Database ++++++" << endl << endl;
    if (NULL == cmd) {
        cout << "[insert] cmd error" << endl;
    }

    if (mysql_real_query(this->dbHandle, cmd,l)) {
        this->erron = 3;
    } else {
        cout << "Database Insert Info: exist, I am updata." << endl << endl;
    }

}
//int to string
/*string mmysql:: inttostring(int in)
 {
 stringstream ss;
 string str;
 ss << in;
 ss >> str;
 return str;
 }*/
char* mmysql::ConvertBinaryToString(char* pBinaryData,int nLen)
{
    static char * s_BinaryData=(char *) malloc(sizeof(char) * nLen * 2 + 256);
    mysql_real_escape_string(this->dbHandle,s_BinaryData,pBinaryData,nLen);
    return s_BinaryData;
}
void mmysql::mysql_re_string( char *end, char *buf,unsigned long int n){
      end+=mysql_real_escape_string(this->dbHandle, end, buf, n);
      cout << "-------end:" << *end<< endl;
}
void mmysql::print_error() {
    switch (this->erron) {
    case 1:
        cout << "连接失败" << mysql_error(this->dbHandle) << endl;
        break;
    case 2:
        cout << "查询失败" << mysql_error(this->dbHandle) << endl;
        break;
    case 3:
        cout << "插入数据失败" << mysql_error(this->dbHandle) << endl;
        break;
    default:
        cout << "错误信息不存在" << endl;
        break;
    }
}

long unsigned int mmysql::mysql_cout() {
    return mysql_affected_rows(this->dbHandle);
}

/*void mmysql::mysql_read() {
 // 释放数据
 if(this->row != NULL) {
 for(int i = 0; i < this->cow; i++ ) {
 delete[] this->tep[i];
 }
 delete[] this->tep;
 }

 MYSQL_RES *result = mysql_store_result(this->dbHandle);
 MYSQL_ROW row;
 int cow_lenth = result->field_count;
 int row_lenth = result->row_count;
 // 数据存储
 this->tep = new string* [row_lenth];
 for( int i=0; i<row_lenth; i++) {
 this->tep[i] = new string[cow_lenth];
 }
 // 行
 this->row = row_lenth;
 // 列
 this->cow = cow_lenth;
 for (int i = 0; i < row_lenth; i++) {
 row = mysql_fetch_row(result);
 for( int j = 0; j < cow_lenth; j++ ) {
 this->tep[i][j] = row[j];
 }
 }
 // 释放数据
 mysql_free_result(result);
 }

 /*int main() {
 mmysql *pInstall = mmysql::makeInstall();
 pInstall->mysql_connect("root", "zjf199694", "test");
 pInstall->mysql_querys("select * from test");
 pInstall->mysql_read();
 pInstall->mysql_querys("select * from test");
 for (int i = 0; i < pInstall->row; i++) {
 for (int j = 0; j < pInstall->cow; j++) {
 cout << pInstall->tep[i][j] << "\t";
 }
 cout << endl;
 }
 pInstall->mysql_read();
 for (int i = 0; i < pInstall->row; i++) {
 for (int j = 0; j < pInstall->cow; j++) {
 cout << pInstall->tep[i][j] << "\t";
 }
 cout << endl;
 }
 cout << "aaa" << endl;
 return 0;
 }*/
 

/*************************************************************************
    > File Name: mysql.h
    > Author: malingyu
    > Mail: [email protected]
 ************************************************************************/
#ifndef __MMYSQL_H_
#define __MMYSQL_H_
 
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <mysql/mysql.h>
using namespace std;
 class mmysql {
 public:
    static mmysql *pInstall; // 连接事例
    MYSQL *dbHandle;
    unsigned int erron;// 错误号
 public:
    static mmysql* makeInstall(); 

    void print_error();// 错误信息
        float float_to_float(float f,int bits) ;//浮点数保留两位小数
    void mysql_connect(const char* user, const char* passwd, const char* dbname);// mysql连接

    int mysql_querys(const char* query,unsigned char * cValue);// sql 查询
    char* ConvertBinaryToString(char* pBinaryData,int nLen);
    long unsigned int  mysql_cout();// 获取更新行数
        void mysql_insert(const char *cmd,unsigned int l);
        void mysql_re_string( char *end, char *buf,unsigned long int n);
        int mysql_querys2(const char* query);
        string inttostring(int in);

 private:
    mmysql();
 public:
    ~mmysql();
 
 };
 
 #endif
 

发布了46 篇原创文章 · 获赞 12 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/malingyu/article/details/90200131
今日推荐