python 往mysql数据库存储照片

新建表img,设置id字段和imgs字段(设置为blob属性,二进制数据)

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Time : 2017/8/18 11:37
  4. # @File : Picture.py
  5. import MySQLdb as mysql
  6. import sys
  7. conn=mysql.connect(host= 'localhost',user= 'root',passwd= 'xxx',db= 'mydata')
  8. fp = open( "./1.jpg")
  9. img = fp.read()
  10. fp.close()
  11. #存入图片
  12. def insert_imgs(img):
  13. # mysql连接
  14. cursor = conn.cursor()
  15. # 注意使用Binary()函数来指定存储的是二进制
  16. # cursor.execute("insert into img set imgs='%s'" % mysql.Binary(img))
  17. cursor.execute( "Insert into img(imgs) values(%s)", (mysql.Binary(img)))
  18. # 如果数据库没有设置自动提交,这里要提交一下
  19. conn.commit()
  20. cursor.close()
  21. # 关闭数据库连接
  22. conn.close()
  23. #提取图片
  24. def select_imgs(img):
  25. cursor=conn.cursor()
  26. cursor.execute( 'select imgs from img')
  27. print cursor.fetchall()
  28. cursor.close()
  29. conn.close()

猜你喜欢

转载自blog.csdn.net/weixin_41896508/article/details/80884032