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()