gpt4 book ai didi

python - 在 Python 中使用按制表符分割会向文本中添加一个字符,这会在 MySQL 中引发错误

转载 作者:行者123 更新时间:2023-11-29 21:52:55 25 4
gpt4 key购买 nike

我想读取制表符分隔文件的行并按制表符分割每一行。所以这是数据:

File.txt:

524550170 {"text":He just proved he has no idea what he's talking about} Sat Oct 31 15:40:00 2015

这是我的代码:

con = mdb.connect('localhost', 'u', 'p', 'testdb');
cur = con.cursor()
cur.execute("CREATE TABLE user_profiles(user_id INT, json_source VARCHAR(1000), user_timestamp TIMESTAMP)")
with open('~/File.txt', 'r') as f:
for row in f:
data = row.split('\t')
query="""insert into user_profiles (user_id, json_source, user_timestamp) values ('%s', '%s', '%s')""" %(data[0], data[1].encode('utf-8'), data[2])
cur.execute(query)

但是当我运行代码并打印 data[1] 时,它会在文本的“he's”部分添加一个\并将其更改为“he\'s”。当我想将其添加到 MySQL 表中时,它给出了 1064 错误,如下所示:

(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 \'s talking about.' at line 2')

知道这里出了什么问题吗?

最佳答案

您正在通过字符串格式手动构建查询 - 这不仅在安全方面存在危险(您容易受到 SQL 注入(inject)),而且还会导致此类问题。

让您的数据库驱动程序担心它并进行参数化查询:

query = """
INSERT INTO user_profiles
(user_id, json_source, user_timestamp)
VALUES
(%s, %s, %s)
"""
cur.execute(query, (data[0], data[1].encode('utf-8'), data[2]))

关于python - 在 Python 中使用按制表符分割会向文本中添加一个字符,这会在 MySQL 中引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com