bitscn.com#include stdafx.h
//是前一篇的姊妹篇
//代码来自网络,我学习整理了一下,测试通过,下面的参数
//需要设置为你自己的
//在dbms中线要创建数据库www,table www,file字段数据类型用longtext即可测试
//测试文件c://test.iso,你可以找任何一个文件修改为即可,我找的是一个exe程序,修改为test.iso而已
//最大测试过加入文件大小为650m(一个正真的iso文件)
//注意:还要修改my.ini文件中的max_allowed_packet字段,我设置的是
//max_allowed_packet = 1024m
//#define host localhost //mysql server
//#define username root
//#define password 674800
//#define database test
//int port = 3306;
#include
#include
#include
#include
#include
#include
#include
#define host localhost //mysql server
#define username root
#define password 674800
#define database www
int port = 3306;
#pragma comment(lib,libmysql.lib)
//得到文件的大小(字节数)
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=null;
off_t size;
mysql *conn=null;
mysql_res *res_set=null;
mysql_row row;
mysql_field *field=null;
int i, flag;
char *sql; //sql语句
file *fp;
char *buf;
int n=256;
char *end;
unsigned long *length;
/* if (argc != 2)
{
printf(usage: %s srcfile/n, argv[0]);
exit(1);
}
*/
filename = c://test.iso;
if ((get_file_size(filename, &size)) == -1) //得到文件的大小
{
perror(get file size );
exit(1);
}
if ((buf = (char *)malloc(sizeof(char)*(size+1))) == null)
{
perror(malloc buf );
exit(1);
}
if ((fp = fopen(filename, rb )) == null) //读文件
{
perror(fopen file );
exit(1);
}
if ((n = fread(buf, 1, size, fp)) {
perror(fread file );
exit(1);
}
sql = (char *)malloc(sizeof(char)*n*2+256); //2n+1+strlen(other sql)
if (sql == null)
{
perror(malloc sql );
exit(1);
}
conn = mysql_init(null);//生产一个mysql对象
if (conn == null)
{
printf(init mysql, %s/n, mysql_error(conn));
exit(1);
}
if ((mysql_real_connect(conn, host, username, password, database, port, null, 0)) == null) //连接服务器
{
printf(connect mysql, %s/n, mysql_error(conn));
exit(1);
}
strcpy(sql, insert into www(id, name, file) values(null, '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, %s/n, mysql_error(conn));
exit(1);
}
if ((mysql_real_query(conn, select file from www where id=1, 31)) != 0)
{
printf(insert failed, %s/n, mysql_error(conn));
exit(1);
}
res_set = mysql_store_result(conn);
fclose(fp);
fp = null;
fp = fopen(c://123.iso, wb );
while ((row = mysql_fetch_row(res_set)) != null)
{
length = mysql_fetch_lengths(res_set);
for (i=0; i{
fwrite(row[0], 1, length[0], fp);
//printf(%s/n,row[0]);
}
}
fclose(fp);
mysql_close(conn);
free(sql);
free(buf);
sql = null;
return 0;
}
运行结果:
bitscn.com