【问题标题】:Can't insert PDF file into MySQL db with Python无法使用 Python 将 PDF 文件插入 MySQL 数据库
【发布时间】:2019-01-19 10:29:56
【问题描述】:

我被困住了。我一直在尝试将 pdf 文件插入 MySQL 数据库,但我不能。我试过 mysql.connector 和 MySQLdb 类。我得到几乎相同的错误。我已经阅读了很多关于这个问题的帖子。我试过逗号,变量也。这是我的代码和错误;

import mysql.connector

db = mysql.connector.connect(host="127.0.0.1", user='root', password='masatablo', db='yukleme')

c  = db.cursor()

acilacak_dosya = open("bizim.PDF", "rb")

yuklenecek_dosya = acilacak_dosya.read()

c.execute ("INSERT INTO pdfler (cizim) VALUES(%s)" %(yuklenecek_dosya))

db.commit()

db.close()

ERROR with mysql.connector:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'b'%PDF-1.4\r%\xe2\xe3\xcf\xd3\r\n4 0 obj\r<</Linearized 1/L 83892/O 6/E 79669/N ' at line 1

ERROR with MySQLdb:
_mysql_exceptions.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 'b'%PDF-1.4\\r%\\xe2\\xe3\\xcf\\xd3\\r\\n4 0 obj\\r<</Linearized 1/L 83892/O 6/E 79669/N ' at line 1")

【问题讨论】:

    标签: python mysql file pdf blob


    【解决方案1】:

    您需要使用参数,而不是字符串插值。

    使用 SQL 进行字符串插值无论如何都容易受到 SQL 注入攻击。

    c.execute("INSERT INTO pdfler (cizim) VALUES (%s)", (yuklenecek_dosya,))
    

    【讨论】:

    • 感谢@AKX,现在可以使用了。这种 SQL 语法有时对我来说真的很有吸引力。我在逗号、括号、变量等之间迷路了。在尝试替代方案时,类似并针对附加文件错误的第一行会使程序员感到困惑。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2021-07-20
    • 2017-10-27
    • 2015-07-22
    • 1970-01-01
    相关资源
    最近更新 更多