python - 如何在Python中使用文本字段到MySQL进行查询?

标签 python mysql

我正在尝试执行 MySQL 表的查询输入,其中字段的类型为 LONGTEXT: 部分代码:

def read_csv_audio():
    with open(audio_file) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            new = []
            new.append(str(row['audio_url']))
            new.append(str(row['google text']))
            new.append(str(row['nuance text']))
            new.append(str(row['checked text']))
            auds.append(new)
            print(row['audio_url'], row['google text'], row['nuance text'], row['checked text'])
    return  auds;

read_csv_audio();

i = 0;
for row in auds:
    add_auds = ("INSERT INTO InnoDB.auds_text (audsid, audio_url, google, nuance, checked) VALUES ("+str(i)+", '"+str(row[0])+"', '"+str(row[1])+"', '"+str(row[2])+", '"+str(row[3])+"') ")
    print(add_auds) # beneath the example1 of print
    cursor.execute(add_auds)
    i += 1

示例1: INSERT INTO InnoDB.auds_text (audsid, audio_url, google, nuance,Checked) VALUES (0, '36649/crawler377116_1_0_20.wav', '如果您知道您想要联系的人的分机号,您已到达竞立媒体纽约总部您可以随时按姓名调用电话,请按 8 获取公司目录以获得即时帮助,请按 0 联系接线员,完成后挂断电话或按井号以获得更多选项', '您已到达 Mediacom 纽约总部,如果您知道您想要联系的人的分机号 您可以随时调用姓名 按 8 获取公司目录以获得即时帮助 按 0 以便接线员在挂出后按提示音记录您的消息,或按井号获取更多选项,'您已到达 Mediacom 纽约总部 如果您知道您想要联系的人的分机号 您可以随时调用 按姓名调用 按 8 获取公司目录以获得即时帮助 按 0 获取接线员挂断电话后按提示音录制您的消息,或按井号获取更多选项beep')

但是,我有一个错误:

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 'you have 
reached the New York headquarters of Mediacom if you know
the extension' at line 1

如何纠正处理文本时的错误?

最佳答案

在生成的查询中,您缺少一个结束单引号:

...pound for more options, 'you have...

我认为这将是你倒数第二个值的结束。

您需要更改此行:

   add_auds = ("INSERT INTO InnoDB.auds_text (audsid, audio_url, google, nuance, checked) VALUES ("+str(i)+", '"+str(row[0])+"', '"+str(row[1])+"', '"+str(row[2])+", '"+str(row[3])+"') ")

对此:

    add_auds = ("INSERT INTO InnoDB.auds_text (audsid, audio_url, google, nuance, checked) VALUES ("+str(i)+", '"+str(row[0])+"', '"+str(row[1])+"', '"+str(row[2])+"', '"+str(row[3])+"') ")

(这是 str(row[2]) 附近的附加单引号)。

编辑:

我建议您更改代码以使用“准备好的语句”。它们不仅可以防止出现这种错误,而且通常是很好的做法,因为您将免费获得清理和类型匹配(这增加了安全性和可靠性)。

如需了解更多信息,您可能想从这个问题开始:Using prepared statements with mysql in python

关于python - 如何在Python中使用文本字段到MySQL进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228368/

相关文章:

python - Numba CUDA `vectorize` 和 `reduce` 装饰器比预期慢

php - 为什么我的变量没有在 php mysqli for 循环中更新?

c# - 在 MonthCalendar 中选择特定日期时如何删除项目

java - Aspose LINQ 文本修剪

python - Pandas - 拆分列存储为 csv

python - 使用 Opencv Python 跟踪多个对象

python - 使用 su 时 CTRL+C 未在 python 脚本中处理

java - 如何将.py导入到java中

php - MYSQL 使用 MATCH 查询选择精确的单词?

mysql - 使用 MySQL 作为 session 存储时的重定向问题