【问题标题】:Programming error when inserting variables from CSV to SQL将变量从 CSV 插入 SQL 时出现编程错误
【发布时间】:2019-11-20 17:59:02
【问题描述】:

我正在网络抓取数据并尝试将其放入我的 SQL 表中。即使我更改了我最初认为错误的内容,此错误仍然出现

ProgrammingError: 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 'type, bathrooms, bedrooms)VALUES('495000', '119 The Dargan Building, Heuston Sou' at line 1

最初是我的数据库表没有足够的字符来存储变量地址,它只设置为 50,但我现在将其更改为 250,但出现了同样的错误。这是现在运行的代码:

import mysql.connector
import csv
#creating csv file
with open ('daftdata.csv','w') as file:

    for row in all_var:
        writer.writerow(row)
    file.close      

mydb = mysql.connector.connect(host='localhost',
user='root',
passwd='123',
database='123')
#prepare cursor
cursor = mydb.cursor()
with open("daftdata.csv", "r") as infh:
    reader =csv.reader(infh)
#csv_data = csv.reader('daftdata.csv')
    for row in reader:
        print(row)
        cursor.execute("INSERT INTO dafttable(price, address, house type, bathrooms, bedrooms)VALUES(%s, %s, %s,%s,%s)",row)

#close the connection to the database.
mydb.commit()
cursor.close()

【问题讨论】:

    标签: mysql python-3.x csv


    【解决方案1】:

    对于char 类型的列,值应该用引号括起来。查看 SQL,这应该适用于地址列,因此应该修改查询以在值周围加上单引号。

    其中包含空格的列名也需要用反引号或引号括起来。这适用于house type 列。一些数据库引擎还支持用空格将列名括起来的方括号。

    cursor.execute("INSERT INTO dafttable(price, address, `house type`, bathrooms, bedrooms)VALUES(%s, '%s', %s, %s, %s)",row)
    

    【讨论】:

    • 如果你只是删除了房子这个词,所以你留下了“类型”,它会消除那个错误,但如果你保留[房子类型]它会保持同样的错误!
    猜你喜欢
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2015-09-28
    • 2013-10-05
    • 1970-01-01
    相关资源
    最近更新 更多