Python 的字符串格式在 mysql 中应用时会引发错误

标签 python mysql python-3.x string-formatting

我用 python 编写了一个脚本,用于从网站上抓取一些数据并将它们存储在 mysql 中。如果我选择两个选项来插入数据,我的脚本会成功完成这项工作:

mycursor.execute("INSERT INTO webdata (name,bubble,review) VALUES ('{}','{}','{}')".format(name,bubble,review))
mycursor.execute("INSERT INTO webdata (name,bubble,review) VALUES (%s,%s,%s)",(name,bubble,review))

但是,当我尝试使用 python's new string formatting 执行相同操作时,它会引发错误如下所示:

mycursor.execute("INSERT INTO webdata (name,bubble,review) VALUES (f'{name},{bubble},{review}')")

它抛出错误:

line 429, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''{name},{bubble},{review}')' at line 1

我哪里出了问题以及如何修复它,因为我非常愿意坚持最后的格式样式?

最佳答案

最好让 MySQL 连接器使用 %s 绑定(bind)变量。这可以避免 SQL 注入(inject)。这是一个工作示例。

import MySQLdb

# set up db connection
dbApi = MySQLdb
connection = MySQLdb.connect(
    host    = <hostname>,
    user    = <databasename>,
    passwd  = password,
    db      = <dbname>,
    port    = 3306,
    charset = "utf8")
cursor = connection.cursor(dbApi.cursors.DictCursor)

# insert records
records = [['George', 'Ten', 'Good'],
           ['Ringo', 'Ten', 'Good'],
           ['Paul', 'Ten', 'Good'],
           ['John', 'Ten', 'Good']]
insert_sql = 'insert into webdata (name, bubble, review) values (%s, %s, %s)'

for record in records:
    cursor.execute(insert_sql, record)

# list record
sql = 'select * from webdata'
cursor.execute(sql)
data = cursor.fetchall()
print 'data:', data

connection.commit()
cursor.close()

关于Python 的字符串格式在 mysql 中应用时会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144535/

相关文章:

mysql - Rails 连接中没有数据库名称

python-3.x - 在 pandas 中分割日期时间

python - 将列表移动到 csv 的更好方法?

python - Django + Celery + SQS 设置。 Celery 通过 ampq 连接到默认的 RabbitMQ

python - 多个周期性定时器

c# - 更新数据库中的值 - MVC

php - laravel 慢查询问题

python - 在单个循环中运行多个测试的最有效方法是什么? Python

python - 使用报纸时如何按类别过滤文章?

python - 密码哈希和验证