Instance Seven:把圖片用二進制存入MYSQL

#!/usr/bin/env python
#--*-- coding:utf-8 --*--
__author__ = 'Kevin'

import MySQLdb as mdb
import sys

try:
    fin = open("django.png")
    img = fin.read()
    fin.close()
except IOError,e:
    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit()

try:
    conn = mdb.connect(host='localhost',user='root',passwd='redhat',db='test')
    cursor = conn.cursor()

    cursor.execute("INSERT INTO Images SET Data='%s'" % mdb.escape_string(img))

    conn.commit()

    cursor.close()
    conn.close()
except mdb.Error,e:
    print "Error %d:%s"%(e.args[0],e.args[1])
    sys.exit(1)

MYSQL 建表:python

CREATE TABLE `test`.`pic` (
 `idpic` int(11) NOT NULL auto_increment,
 `caption` varchar(45) NOT NULL default '',
 `img` longblob NOT NULL,
 PRIMARY KEY (`idpic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; django

相關文章
相關標籤/搜索