python - 无法使用 Python 将 PDF 文件插入 MySQL 数据库
问题描述
我被困住了。我一直在尝试将 pdf 文件插入 MySQL db,但我不能。我试过 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")
解决方案
您需要使用参数,而不是字符串插值。
无论如何,使用 SQL 进行字符串插值很容易受到 SQL 注入攻击。
c.execute("INSERT INTO pdfler (cizim) VALUES (%s)", (yuklenecek_dosya,))
推荐阅读
- python - 在文件名中查找交替(字母或数字)+字母模式
- laravel - 如何检查正在执行的控制器数据对象?
- swift - 如何更改 Tableview 的 UIContextualAction 的图像色调颜色?
- java - MongoDB JAVA:查询时是否有任何可能的异常?
- mysql - 将 Yii2 中的变量插入数据库
- c# - 名称空间中不存在名称 xxx DataProvider
- centos7 - CentOS 7 - Payara 5 无法在端口 80 上运行
- python - 随机森林的表现比其他方法好得多
- python - 为字典python中的每个键选择最大值
- r - 是否有用于根据额外列更改部分变量的 dplyr 函数?