MySQL存儲圖片的二進制,其字段設置爲blob屬性,二進制數據mysql
1 import pymysql 2 import sys 3 4 conn=pymysql.connect(host='localhost',user='root',passwd='xxx',db='mydata')
1 fp = open("./1.jpg") 2 img = fp.read() 3 fp.close()
1 def insert_imgs(img): 2 # mysql鏈接 3 4 cursor = conn.cursor() 5 # 注意使用Binary()函數來指定存儲的是二進制 6 # cursor.execute("insert into img set imgs='%s'" % mysql.Binary(img)) 7 cursor.execute("Insert into img(imgs) values(%s)", (mysql.Binary(img))) 8 # 若是數據庫沒有設置自動提交,這裏要提交一下 9 conn.commit() 10 cursor.close() 11 # 關閉數據庫鏈接 12 conn.close()
1 def select_imgs(img): 2 cursor=conn.cursor() 3 cursor.execute('select imgs from img') 4 print cursor.fetchall() 5 cursor.close() 6 conn.close()
版權聲明:本文爲CSDN博主「Coder_py」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/Coder_py/article/details/77368034sql