Python, sqlite3 syntax error
Сделал простую программу, но не могу понять почему один раз из пяти все работает и в базу добавляются данные, а остальные четыре ошибка:
Traceback (most recent call last):
File "D:\python\engdict.py", line 27, in <module>
addInDB()
File "D:\python\engdict.py", line 24, in addInDB
cursor.execute(f"INSERT INTO All_Words VALUES (NULL, '{word}', '{short}', '{long_}')")
sqlite3.OperationalError: near "s": syntax error
Вот код:
import requests
from bs4 import BeautifulSoup
import sqlite3
def getWord():
url = 'https://www.vocabulary.com/dictionary/randomword'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
h1 = soup.find('h1', class_='dynamictext').text
shortMeaning = soup.find('p', class_='short').text
longMeaning = soup.find('p', class_='long').text
full = [h1, shortMeaning, longMeaning]
return full
def addInDB():
full = getWord()
word = full[0].capitalize()
short = full[1]
long_ = full[2]
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute(f"INSERT INTO All_Words VALUES (NULL, '{word}', '{short}', '{long_}')")
conn.commit()
addInDB()
Upd: Проблема была в форматировании строк, ниже - код, который работает нормально.
import requests
from bs4 import BeautifulSoup
import sqlite3
import json
def getWord():
url = 'https://www.vocabulary.com/dictionary/randomword'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
h1 = soup.find('h1', class_='dynamictext').text
shortMeaning = soup.find('p', class_='short').text
longMeaning = soup.find('p', class_='long').text
full = [h1, shortMeaning, longMeaning]
return full
def addInDB():
full = getWord()
print(full)
word = full[0].capitalize()
short = json.dumps([full[1]])
long_ = json.dumps([full[2]])
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO All_Words VALUES (NULL, ?, ?, ?)", [word, short, long_])
conn.commit()
addInDB()