在学数据库时老师布置的题目,其中我省了很多事,很多判断没有加.仅供参考~~
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
/*
函数名:savepicture
函数作用:存储图片
参数:无
返回值:无
*/
void savepicture()
{
FILE* fp = fopen("pic.jpg","r+");//文件流读取图片文件
if (fp == NULL)
{
printf("fopen fail\n");
exit(-1);
}
char buf[1024*1024];//存储图片二进制代码,图片大小不超过1M
char binary[2*1024*1024+1];//用来存储转义后的图片的二进制代码
memset(binary,0,sizeof(binary));//初始化数组binary
memset(buf,0,sizeof(buf));//初始化数组buf
unsigned long pic_length,binary_length;
pic_length = fread(buf,1,sizeof(buf),fp);//pic_length图片读取的实际大小
fclose(fp);//关闭fp文件流指针
MYSQL * handler;
handler = mysql_init(NULL);
if (handler == NULL)
{
printf("mysql_init error:\n");
exit(-1);
}
if (mysql_real_connect(handler,"localhost","root",NULL,"lkd1001db",3306,NULL,0) == NULL)
{
printf("%s\n",mysql_error(handler));
exit(-1);
}
<pre name="code" class="cpp"> //pdata字段名 类型是longblob,你们可以尝试下这里写blob图片最大为多少才能完整输出
mysql_query(handler,"create table if not exists picture(pdata longblob)"); //unsigned long mysql_real_escape_string(MYSQL *mysql, char *to, const char *from, unsigned long length) //返回值是个unsigned long转义后binary的数组长度 binary_length
= mysql_real_escape_string(handler,binary,buf,pic_length);//转义后的实际大小 char sql[2*1024*1024+50];//存储最终语句 sprintf(sql,"insert into picture values('%s')",binary); unsigned long len; len = strlen(sql);//最终语句的实际大小 mysql_real_query(handler,sql,len); mysql_close(handler);}/*
函数名:printpicture 函数作用:打印图片 参数:无 返回值:无 */ void printpicture(){ FILE* fp ; fp = fopen("pic2.jpg","w+"); MYSQL * handler; handler = mysql_init(NULL); if (handler == NULL) { printf("mysql_init error:\n"); exit(-1); } if (mysql_real_connect(handler,"localhost","root",NULL,"lkd1001db",3306,NULL,0)
== NULL) { printf("%s\n",mysql_error(handler)); exit(-1); } mysql_query(handler,"select * from picture"); MYSQL_RES * res = mysql_store_result(handler); int row = mysql_num_rows(res);//行数 MYSQL_ROW vrow; vrow=mysql_fetch_row(res);//提取一行 unsigned long *length;//这里length是个指针
length = mysql_fetch_lengths(res); fwrite(vrow[0],1,length[0],fp); fclose(fp); mysql_close(handler); mysql_free_result(res);//释放结果集}