Store binary data to MySQL using escape_string in MySQLdb

mediumblob can store data less than 16M:

 

 mysql> desc images;
+-------+------------+------+-----+---------+----------------+
| Field | Type       | Null | Key | Default | Extra          |
+-------+------------+------+-----+---------+----------------+
| id    | int(10)    | NO   | PRI | NULL    | auto_increment |
| image | mediumblob | YES  |     | NULL    |                |
+-------+------------+------+-----+---------+----------------+

 

#!/usr/bin/env python
# --*-- coding=utf-8 --*--

 

import MySQLdb
conn = MySQLdb.connect('192.168.100.168', 'root', 'pass', 't')
cursor = conn.cursor()

f = open('poppy.jpg', 'rb')
bin_data = f.read()
f.close()


stmt = 'insert into images (image) values("%s")' % (conn.escape_string(bin_data))
cursor.execute(stmt)

 

or  using special format below, caution, there is no quoted characters enclosed for %s:

 

stmt = 'insert into images (image) values(%s)'
cursor.execute(stmt, (bin_data))

 

 

 

你可能感兴趣的:(Linux)