有人可以解释一下这是什么意思吗?
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 '[' at line 1
是在我的代码中“ [”附近的某个地方,我做错了什么吗?
此代码块中发生错误。我不明白为什么要说它在“ [”附近,因为那段代码事先工作正常?谢谢
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq
p_list = []
n_list = []
h_list = []
ba_list = []
be_list = []
all_var =[]
for page in range(20,300,20):
my_url = "https://www.daft.ie/ireland/property-for-sale/?
offset=20".format(page)
#open connection and grab webpage
uClient = uReq(my_url)
#store html in a variable
page_html = uClient.read()
#close web connection
uClient.close()
#parse html
soup = BeautifulSoup(page_html, "html.parser")
print(soup)
#grabs listings house information
listings = soup.findAll("div",
{"class":"FeaturedCardPropertyInformation__detailsContainer"})
for container in listings:
#extracting price
price = container.div.div.strong.text
price = price.strip('AMV: €')
price = price.strip('Reserve: €')
price = price.replace(',', "")
price = int(price)
p_list.append(price)
#location
location = container.div.find("a {"class":"PropertyInformationCommonStyles__addressCopy--link"}).text
n_list.append("'"+location+"'")
#house type
house = container.div.find("div",
{"class":"QuickPropertyDetails__propertyType"}).text
h_list.append("'"+house+"'")
#number of bathrooms
bath_num = container.div.find("div {"class":"QuickPropertyDetails__iconCopy--WithBorder"}).text
#makes str and int
bath_num = int(bath_num)
ba_list.append(bath_num)
#number of bedrooms
bed_num = container.div.find("div", {"class":"QuickPropertyDetails__iconCopy"}).text
bed_num = int(bed_num)
be_list.append(bed_num)
#makes str and int
all_var.append((price, location, house, bath_num, bed_num))
a_v = str(all_var)
#connecting to database
import mysql.connector
d_b = mysql.connector.connect(host = "localhost", user = "myaccount", passwd = "mypassword", database = "database",)
print(d_b)
mycursor = d_b.cursor(buffered=True)
#create database
#mycursor.execute("CREATE DATABASE daftdatabase")
#create table
#mycursor.execute("CREATE TABLE DaftTable(price Integer(10), location
VARCHAR(50), type VARCHAR(20), bedrooms INTEGER(2), bathrooms
INTEGER(2))")
show_t = mycursor.execute("SHOW TABLES")
for var in a_v:
data = mycursor.execute("INSERT INTO DaftTable(price, location, type, bathrooms, bedrooms) VALUES"+var)
mycursor.commit()
每次我修复错误时,都会不断发生另一个错误,而我只想了解该错误告诉我什么以及如何解决该错误?
答案 0 :(得分:0)
错误告诉您您以错误的方式编写SQL。
首先,您应该对插入的内容进行转义/清理。 如果您这样编写字符串,那么充其量极有可能在某个时候失败(例如,由于使用了不转义的单引号),最糟糕的是,如果您在代码的其他部分中这样做,有一个SQL注入漏洞
第二,即使您逃脱了一切,仍然无法正常工作。
您要获取值,将其放入列表中,然后将其字符串化:
all_var.append((price, location, house, bath_num, bed_num))
a_v = str(all_var)
这意味着如果您有类似的东西
[
(1, 2, 3, 4),
(5, 6, 7, 8),
]
对于您的值,您正在将其转换为字符串[(1, 2, 3, 4), (5, 6, 7, 8)]
,并且for
循环将迭代该字符串的单个字符。
第一个字符是[
,因为您正在尝试执行,因此会提示您错误
INSERT INTO DaftTable(price, location, type, bathrooms, bedrooms) VALUES[")
因此,您需要不对值进行字符串化并以适当的方式编写字符串(如果您确实要编写字符串而不是使用某种类型的SQL库,请至少使用%s
语法)。