您的位置:首页 > 编程语言 > Python开发

python将图片以二进制存入mysql并取出来

2013-04-22 21:58 591 查看
import MySQLdb as mdb

class BlobData:

def __init__(self):

self.conn = mdb.Connect('localhost', 'root', '123456', 'test')

def __del__(self):

try:

self.conn.close()

except:

print "close database error"

def closedb(self):

self.conn.close()

def setup(self):

cursor = self.conn.cursor()

try:

cursor.execute("Create table if not exists picture(id int(3) primary key auto_increment, pic_name varchar(20), data longblob) engine=MyISAM default charset = utf8;")

except Exception, e:

print "create database error:", e

finally:

cursor.close()

def teardown(self):

cursor = self.conn.cursor()

try:

cursor.execute("drop table picture")

except Exception, e:

print "drop database error", e

finally:

cursor.close()

def testRWBlobData(self):

fil = open("c:/web.jpg", 'rb')

b = fil.read()

fil.close()

cursor = self.conn.cursor()

cursor.execute("Insert into picture(data) values(%s)", (mdb.Binary(b)))

cursor.execute("select data from picture order by id desc limit 1")

d = cursor.fetchone()[0]

cursor.close()

f = open("c:/images.jpg", 'wb')

f.write(d)

f.close()

if __name__ == "__main__":

test = BlobData()

try:

test.setup()

test.testRWBlobData()

test.teardown()

finally:

test.closedb()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: