python 如何使用 PyMYSQL 将数据存储到数据库中

How to store data into database using PyMYSQL in python

我正在抓取一个网站并从中获取公司的详细信息,现在我试图将数据存储到数据库中。但是我收到了一些错误,例如

raise InternalError(errno, errorvalue)
pymysql.err.InternalError: (1054, "Unknown column 'companyaddress' in 'field list'")

这是我的代码

for d in companydetail:
    lis = d.find_all('li')
    companyname = lis[0].get_text().strip()
    companyaddress = lis[1].get_text().strip()
    companycity = lis[2].get_text().strip()
try:
   companypostalcode = lis[3].get_text().strip()
   companypostalcode = companypostalcode.replace(",","")

except:
   companypostalcode = lis[3].get_text().strip()
try:
   companywebsite = lis[4].get_text().strip()
except IndexError:
   companywebsite = 'null'
print (companyname)                          
print (companyaddress)
print (companycity)
print (companypostalcode)
print (companywebsite)
try:
   with connection.cursor() as cursor:
   print ('saving to db')
   cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")
   connection.commit()
   connection.close()                            

我正在获取我想要的数据,但我无法将数据存储到数据库中。 我在 print (companyname) 和 print (campanyaddress) 时得到的结果是:

NINGBO BOIGLE DIGITAL TECHNOLOGY CO.,LTD.
TIANYUAN INDUSTRIAL ZONE CIXI NINGBO
ZHEJIANGNINGBO
315325
http://www.boigle.com.cn

您不能像现在这样简单地在查询字符串中使用变量名:

cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")

相反,将您的变量传递到查询中,使其 参数化:

params = (companyname, companyaddress, companycity, companypostalcode, companywebsite)
cursor.execute("""
    INSERT INTO 
        company
        (companyname, address, city, pincode, website) 
    VALUES 
        (%s, %s, %s, %s, %s)
""", params)

   cursor.execute("INSERT INTO company(companyname,address,city,pincode,website) VALUES (companyname,companyaddress,companycity,companypostalcode,companywebsite)")

第二个括号中的值被解释为 table 字段,而不是 python 变量。尝试

   cursor.execute("""INSERT INTO company(
           companyname,address,city,pincode,website) 
       VALUES (%s, %s, %s, %s, %s)""",
       (companyname, companyaddress, companycity, 
        companypostalcode, companywebsite))

相反。您可能还想就此咨询 the docs