Discover Discover - 13 days ago 7
Python Question

Inserting in sqlite with each thread in Python

I am trying to insert in a SQLITE database the new response I get from my API on each thread for 3 different cities. However I get an error on the execute command as I seem to be unable to insert the values as a weather['main']['temp'] or even if I give it to a variable y = weather['main']['temp'] it still doesn't work. I would welcome any suggestions

import requests
import json
import threading
import time
from threading import Thread
import sqlite3
conn = sqlite3.connect("dfg.db",check_same_thread = False)
c = conn.cursor()

def main():
createT()
threading.Timer(10, giveVelingrad).start()
threading.Timer(15, giveSofia).start()
threading.Timer(25, givePlovdiv).start()

def createT():
c.execute('CREATE TABLE IF NOT EXISTS tabl(city TEXT, temp REAL)')

def giveVelingrad():
city = "Velingrad"
response = requests.get("http://api.openweathermap.org/data/2.5/weather?q=" +city+ "&appid=2e8707d1eb97fbbba33ef766d9ed80ac&units=metric")
weather = response.json()
www = time.strftime("%d.%m.%y %H.%M.%S")
y = weather['name']
z = weather['main']['temp']
c.execute("INSERT INTO tabl VALUES (?, ?)",y,z )
conn.commit()
c.close()
conn.close()
print("\n",www)
print("The weather for ", weather['name'])
print("The temperature is ", weather['main']['temp'])

def giveSofia():
city = "Sofia"
response = requests.get("http://api.openweathermap.org/data/2.5/weather?q=" +city+ "&appid=2e8707d1eb97fbbba33ef766d9ed80ac&units=metric")
weather = response.json()
www = time.strftime("%d.%m.%y %H.%M.%S")
print("\n",www)
print("The weather for ", weather['name'])
print("The temperature is ", weather['main']['temp'])

def givePlovdiv():
city = "Plovdiv"
response = requests.get("http://api.openweathermap.org/data/2.5/weather?q=" +city+ "&appid=2e8707d1eb97fbbba33ef766d9ed80ac&units=metric")
weather = response.json()
www = time.strftime("%d.%m.%y %H.%M.%S")
print("\n",www)
print("The weather for ", weather['name'])
print("The temperature is ", weather['main']['temp'])


if __name__ == '__main__':
main()

Answer

You need to pass in parameters as one sequence: c.execute("INSERT INTO tabl VALUES (?, ?)", [y, z]) or c.execute("INSERT INTO tabl VALUES (?, ?)", (y, z)), not as two separate arguments.

You also don't want to share the connection between threads, and certainly don't share cursors between threads; I'd use a separate connection per thread. See How to share single SQLite connection in multi-threaded Python application

Comments