往mysql插入二进制图片1064错误 conn = pymysql.connect(*) cur = conn.cursor() os.chdir(/home/jibo/zxcsSpider/images/full/) list = os.listdir() count1 = 0 for imagename in list: count1 += 1 f = open(imagename, rb) data = f.read() f.cl
conn = pymysql.connect(*) cur = conn.cursor() os.chdir('/home/jibo/zxcsSpider/images/full/') list = os.listdir() count1 = 0 for imagename in list: count1 += 1 f = open(imagename, 'rb') data = f.read() f.close() imagepath = '/home/images/full/' + imagename imagebin = pymysql.Binary(data) sql = "insert into images(imagename,imagepath,imagebin) values('%s', '%s', '%s')" cur.execute(sql, (imagename, imagepath, imagebin)) conn.commit() print('image:' + str(count1)) cur.close() conn.close()
上面代码运行时,mysql会报1064错误:
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'cecedd67b6d4716bdbab9fac36e0b2ad1c81cbac.jpg'', ''/home/images/f' at line 1")
修改:将('%s', '%s', '%s')改为(%s, %s, %s)
conn = pymysql.connect(*) cur = conn.cursor() os.chdir('/home/images/full/') list = os.listdir() count1 = 0 for imagename in list: count1 += 1 f = open(imagename, 'rb') data = f.read() f.close() imagepath = '/home/images/full/' + imagename imagebin = pymysql.Binary(data) sql = "insert into images(imagename,imagepath,imagebin) values(%s, %s, %s)" cur.execute(sql, (imagename, imagepath, imagebin)) conn.commit() print('image:' + str(count1)) cur.close() conn.close()
再次运行成功;
因为某些文档干扰,在网上找了大半天才找倒原因问题,pymysql中的参数%s是不用加''号的,当我们插入字符串的时候可能不会应为这个问题报错,因为字符串本身也有引号,再次加引号不会报错,但二进制格式的话就会报错
图片如何以二进制存入mysqlMYSQL 支持把图片存入数据库,也相应的有一个专门的字段 BLOB (Binary Large Object)
首先要在你的mysql数据库中创建一个表,用于存储图片
CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
然后用python代码将本地的图片存到数据库中
# coding=utf-8 import MySQLdb import sys try: fin = open("/home/dsq/tb/8.jpg") #打开本地图片,路径要写自己的 img = fin.read() fin.close() #读取结束,关闭文件 except IOError as e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) #出现错误打印错误并退出 try: conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="#你的数据库密码#", db="数据库名") #连接到数据库 cursor = conn.cursor() #获取cursor游标 cursor.execute("INSERT INTO Images SET Data='%s'" % MySQLdb.escape_string(img)) #执行SQL语句 conn.commit() #提交数据 cursor.close() conn.close() #断开连接 except MySQLdb.Error,e: conn.rollback() print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) #出现错误,自动回滚,打印错误并退出
发现图片成功存储到数据库中