Home > Backend Development > Python Tutorial > python3图片转换二进制存入mysql

python3图片转换二进制存入mysql

WBOY
Release: 2016-06-16 08:45:56
Original
1711 people have browsed it

首先,在数据库中创建一个表,用于存放图片:

复制代码 代码如下:

CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);


然后运行如下PYTHON代码进行:

复制代码 代码如下:

# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
try:
    #用读文件模式打开图片
    fin = open("../web.jpg")
    #将文本读入img对象中
    img = fin.read()
    #关闭文件
    fin.close()
except IOError, e:
    #如果出错,打印错误信息
    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
try:
    #链接mysql,获取对象
    conn = mdb.connect(host='localhost',user='root',passwd='root', db='test')
    #获取执行cursor
    cursor = conn.cursor()
    #直接将数据作为字符串,插入数据库
    cursor.execute("INSERT INTO Images SET Data='%s'" % mdb.escape_string(img))
    #提交数据
    conn.commit()
    #提交之后,再关闭cursor和链接
    cursor.close()
    conn.close()
except mdb.Error, e:
    #若出现异常,打印信息
    print "Error %d: %s" % (e.args[0],e.args[1])

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template