把图片写入数据库并之后能完整输出的图片

本文展示了一个使用C语言编写的程序示例,该程序能够将一张图片存储到MySQL数据库中,并从数据库中检索出来。具体步骤包括读取图片文件、进行转义处理、连接MySQL数据库、创建表、插入图片数据以及查询并输出图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在学数据库时老师布置的题目,其中我省了很多事,很多判断没有加.仅供参考~~

#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);//释放结果集}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值