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 'cecedd67b6d4716bdd/home9fac36e0b2ad1c81cbac.jpg''#/d/home/136e0b2ad1c81cbacac.jpg''#/bab/d
修改:將('%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是不用加''號的,當我們插入字符串的時候可能不會應為這個問題報錯,因為字符串本身也有引號,再次加引號不會報錯,但二進位格式的話就會報錯
圖片如何以二進位存入mysql
首先要在你的mysql資料庫中建立一個表,用於儲存圖片
rrreee然後用python程式碼將本地的圖片儲存到資料庫中
CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
發現圖片成功儲存到資料庫中
以上是python3往mysql插入二進位圖片出現1064錯誤如何解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!