1

I update the variable directly in the database (manually). But, the code in the while loop never updates the variable because it is in a loop, I would like to know what I should do to get the new value.

Maybe exit the loop and reopen it? I tried with break, but it closes the script.

import sqlite3

def read_data(data, table):
    con = sqlite3.connect("settings.db")
    cur = con.cursor()
    read_data.row = cur.execute(f"SELECT {data} FROM {table}").fetchall()[0][0]

read_data("data", "eyes")
eyes = read_data.row

while True:
    read_data("data", "eyes")
    eyes_loop = read_data.row

    if eyes_loop != eyes:
        print("Eyes changed")
        break

    else:
        print("Eyes not changed")
        continue
martineau
  • 119,623
  • 25
  • 170
  • 301
principemestizo3
  • 161
  • 3
  • 13

2 Answers2

3

There are multiple things not quite right:

  1. You should close your connection if you establish it inside a function.
  2. You should return values instead of overwriting them outside the scope. Nasty side effects can occur.
import sqlite3

def read_data(data, table):
    con = sqlite3.connect("settings.db")
    cur = con.cursor()
    data = cur.execute(f"SELECT {data} FROM {table}").fetchall()[0][0]
    con.close()
    return data


eyes = read_data("data", "eyes")

while True:
    eyes_loop = read_data("data", "eyes")

    if eyes_loop != eyes:
        print("Eyes changed")
        break

    else:
        print("Eyes not changed")
        continue
JJ.
  • 76
  • 5
-1

The function you are using takes time to connect with database and send data back and forth. This code runs asynchronously so the loop runs and it runs past the read_data() to avoid this use async/await.

Soyokaze
  • 157
  • 8