[英]Inserting data using python loop to sql table
我寫了一個 web 抓取代碼來從一個到目前為止工作的網站獲取一些數據。 我將Python連接到SQL因為我需要保存數據MySQL 。 The connection between Python and SQL is working fine, I created the SQL table with Python which I commented on the code below. 我的問題是在將數據插入SQL表時,插入腳本應該可以正常工作,但是我遇到了無法糾正的語法錯誤。 有人有想法嗎?
這是代碼:
import mysql.connector
db_connection = mysql.connector.connect(
host="141.45.91.40",
user="s0566293",
passwd="*******",
database="s0566293_projekt"
)
db_cursor = db_connection.cursor()
#Here creating database table as film'
#db_cursor.execute("CREATE TABLE Filme (filmName VARCHAR(255))") #already exists.
#Get database table'
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
print(table)
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import requests
import re
my_url = 'https://www.berlin.de/kino/_bin/azfilm.php'
# opening up connection , grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
#html parsing
page_soup = soup(page_html,"html.parser")
# grab any Zeichen
az = page_soup.findAll("div",{"class":"block"})
fil = az[0]
sei = fil.findAll("li")
for s in sei:
i=s.text
if (i == '#'):
continue
else:
seite = "https://www.berlin.de/kino/_bin/azfilm.php/de/{}".format(i)
r = requests.get(seite)
seiten_soup = soup(r.content, 'html.parser')
#print page url
#print("-------------------------------------------------------\n" + seite)
#Filme jeder Seite
# opening up connection , grabbing the page
uClient = uReq(seite)
page_html = uClient.read()
uClient.close()
#html parsing
page_soup = soup(page_html,"html.parser")
# grab any film
az = page_soup.findAll("div",{"class":"inner"})
fil = az[0]
filme = fil.findAll("li")
for film in filme:
db_cursor.execute("INSERT INTO Filme(filmName) VALUES("+film.contents[0].contents[0]+")")
db_cursor.execute("SHOW Filme")
#print(film.contents[0].contents[0])
連接變量時,您不會在名稱周圍加上引號。
但是你不應該將變量連接到 SQL,你應該使用占位符。
db_cursor.execute("INSERT INTO Filme(filmName) VALUES(%s)", (film.contents[0].contents[0],))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.