python的字符串格式在mysql中应用时抛出错误

wfveoks0  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(482)

我已经用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的新字符串格式执行相同操作时,它会抛出一个错误,如下所示:

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

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

zi8p0yeb

zi8p0yeb1#

最好让mysql连接器使用%s绑定变量。这避免了sql注入。这里是一个工作的例子。

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()
a7qyws3x

a7qyws3x2#

如果您想编写不易受sql注入漏洞攻击的代码,就不能将f字符串用于数据库,就这么简单。

相关问题