In general, we store pictures in the file system, but only in the database to store the file path, but sometimes there are special needs: the picture binary into the database.
Today we're using the Python+mysql way.
MYSQL is to support the image into the database, but also corresponding to a dedicated field BLOB (binary Large object), that is, a larger binary object
There is also a larger longblob of binary deposit;
Note here: Try to set the field as large as possible, because if you set the length of the word to be small, the picture will show only part of the situation. Second: If the amount of data is large, try to avoid this way, because MySQL query for big data is very slow.
The following code:
| 123456789101112131415161718192021222324252627 |
#!/usr/bin/python#-*- coding: UTF-8 -*- import MySQLdb as mysqlimportsystry: #读取图片文件 fp =open("./test.jpg") img =fp.read() fp.close()exceptIOError,e: print"Error %d %s"%(e.args[0],e.args[1]) sys.exit(1)try: #mysql连接 conn =mysql.connect(host=‘localhost‘,user=‘root‘,passwd=‘123456‘,db=‘test‘) cursor =conn.cursor() #注意使用Binary()函数来指定存储的是二进制 cursor.execute("INSERT INTO images SET data=‘%s‘" %mysql.Binary(img)) #如果数据库没有设置自动提交,这里要提交一下 conn.commit() cursor.close() #关闭数据库连接 conn.close()exceptmysql.Error,e: print"Error %d %s"%(e.args[0],e.args[1]) sys.exit(1) |
MySQLdb operation MySQL BLOB value