验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

python3.x怎么向mysql存储图片并显示

阅读:1126 来源:乙速云 作者:代码code

python3.x怎么向mysql存储图片并显示

      python3向mysql存储图片并显示


      首先我们建好数据库,然后进入cmd,在系统操作框中输入ipconfig显示本机的ip信息


      python3.x怎么向mysql存储图片并显示


      主要要获知本机ip地址。


      我们需要在mysql中先建立一个表,并把字段设置好,输入下面代码:

      create table image(id int(5)auto_increment primary key,image1 mediumblob)

      然后我们需要打开python,我使用的是pycharm。

      我们需要用到的包是 pymysql

      我们把所要导进去的图片拖进pycharm中,设置好名称以便一会使用,我们首先读取图片文件(使用二进制读取方法,‘rb’)

      f = open('2.jpg','rb')
      img = f.read()
      f.close()

      然后我们与mysql进行连接:

      gao = pymysql.connect(
                             host='157.142.13.27',#本机或其他机器的ip地址
                             port=3306,#接口
                             user='root',#用户名
                             passwd='******',#密码
                             db='gao',#你所使用的数据库
                             charset='utf8',#编码方式
                             use_unicode=True, )

      创建游标,使用cursor函数:

      g = gao.cursor()

      读取图片信息

      f = open('2.jpg','rb')data = f.read()

      使用execute函数修改数据库:

      g.execute('insert into image(image1) values (%s)'%data)

      注意:如果一直显示没有权限连接数据库,我们先登录数据库,并进入你的mysql数据库,然后改变host:

      update user set host = '%' where user = 'root';mysql>flush rivileges

      注意在最后一定要关闭游标和连接。

      写完我们可以在数据库中查看我们设的表中的内容,但由于解码方式,我们看到的是一堆乱码,我们可以在pycharm中显示图片。

      python将图片导入mysql数据库

      # 今天需要用Python实现将图片导入MySQL数据库。看了看网上的一些写法,自己也过一遍,记录下来,以防忘记。
       
      # 功能:将图片导入到MySQL数据库
      import sys
      import pymysql
      from PIL import Image
      import os
       
      path = "./"
       
      #读取图片文件
      fp = open("./陈丹江-420381198212068517.JPG", 'rb')
      img = fp.read()
      fp.close()
       
      #建立一个MySQL连接
      database = pymysql.connect(host="10.31.143.6", user="root", passwd="******", db="aaa", charset='utf8')
      # 存入图片
      # 创建游标
      cursor = database.cursor()
      #注意使用Binary()函数来指定存储的是二进制
      sql = "INSERT INTO vbp_person_ext (person_id, image, img_type) VALUES  (%s, %s, %s);"
      args = ('39', img, 'JPG')
      cursor.execute(sql, args)
       
      database.commit()
      # 关闭游标
      cursor.close()
      # 关闭数据库连接
      database.close()
      print("============")
      print("Done! ")

      数据库表 vbp_person_ext 包含三个字段:person_id, image, img_type(image是图片信息)

      过程中遇到问题

      报错:

      UnicodeEncodeError: 'latin-1' codec can't encode characters in position 303-304: ordinal not in range(256)

      解决:增加 charset='utf8

    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>