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

c/vc/c++ 将文件保存到mysql数据库(longblob类型)

2012-03-16 13:39 621 查看
网上的都是废话一大堆,好不容易修改的可以用了,测试了一下,写如几百MB的文件没问题,至于几百GB的,不得而知的,蛋疼的请自己尝试。

// mysqlwritefile.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include "winsock.h"

#include "mysql.h"

#include "stdio.h"

#include "io.h"

#include "sys/stat.h"

#include <FCNTL.H>

#include "windows.h"

#include<stdlib.h>

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

#define INSERT_QUERY "INSERT INTO tablename(id, file) VALUES(1, ?)"

MYSQL *conn;

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(int argc, char *argv[])

{

char *filename;

off_t size;

MYSQL_RES *res_set;

MYSQL_ROW row;

MYSQL_FIELD *field;

int i, flag;

char *sql;

FILE *fp;

char *buf;

int n=0;

char *end;

unsigned long *length;

filename = "c:\\a.7z";

if ((get_file_size(filename, &size)) == -1) {

perror("get file size" );

return 1;

}

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;

}

conn = mysql_init(NULL);

if (conn == NULL) {

printf("init mysql, %sn", mysql_error(conn));

return 1;

}

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

printf("connect mysql, %sn", mysql_error(conn));

return 1;

}

strcpy(sql, "insert into tablename2(id, name, file) values(2, 'peter', " );

end = sql;

end += strlen(sql); //point sql tail

//convert NUL(ASCII 0)、'n'、'r'、''’、'''、'"'和Control-Z and so on

*end++ = '\'';

end += mysql_real_escape_string(conn, end, buf, n);

*end++ = '\'';

*end++ = ')';

flag = mysql_real_query(conn, sql, (unsigned int)(end-sql));

if (flag != 0) {

printf("insert failed, %sn", mysql_error(conn));

return 1;

}

if ((mysql_real_query(conn, "SELECT file FROM tablename where id=5", 31)) != 0) {

printf("insert failed, %sn", mysql_error(conn));

return 1;

}

res_set = mysql_store_result(conn);

fclose(fp);

fp = NULL;

fp = fopen("foo.bk", "wb" );

while ((row = mysql_fetch_row(res_set)) != NULL)

{

length = mysql_fetch_lengths(res_set);

for (i=0; i<mysql_num_fields(res_set);i++)

{

fwrite(row[0],1,length[0],fp);

}

}

fclose(fp);

mysql_close(conn);

free(sql);

sql = NULL;

return 0;

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