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

时间:2018-11-04 19:25:22

标签: 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

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

3 个答案:

答案 0 :(得分:2)

更好的是让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()

答案 1 :(得分:1)

如果要编写对SQL注入漏洞不敏感的代码,则不能对数据库使用f字符串。

答案 2 :(得分:0)

总有其他选择。尽管不建议将 mycursor.execute(f"INSERT INTO webdata (name,bubble,review) VALUES ('{name}','{bubble}','{review}')") 用于数据库或使用该数据库是安全的,但是仍然可以这样做。检查一下:

browser_profile = webdriver.FirefoxProfile()
browser_profile.set_preference("dom.webnotifications.enabled", False)
driver = webdriver.Firefox(firefox_profile=browser_profile)