Showing info from a Sqlite database in 3 different QListWidget - python

My objective is to show a kanban table by day, so the user could save their pending, in process or completed tasks for each day in the calendar. My program look as follows:
Every list is a QListWidget, where the user can add a new pending task by right clicking over them or move the tasks from the "Pendientes" list to the "En proceso" list or the "Completadas" list.
Now, for saving the task for every date of the QCalendarWidget, I'm trying to use a sqlite database that looks like this:
where the "tareas" column shows the tasks, "lista" shows a number corresponding to each of my three QListWidgets (0 = "Pendientes"; 1 = "En proceso" and 2 = "Completadas") and "fecha" shows the date. I'm able to show every task in the corresponding list by date just fine with this function, but only the tasks that I added directly in the Sqlite Browser:
def updateTaskList(self, date):
self.lista_pendientes.clear()
self.lista_enprogreso.clear()
self.lista_completadas.clear()
db = sqlite3.connect("todo.db")
cursor = db.cursor()
query = "SELECT tarea, lista FROM tareas WHERE fecha = ?"
row = (date,)
results = cursor.execute(query, row).fetchall()
for tarea, list in results:
item = QListWidgetItem(tarea)
if list == 0:
self.lista_pendientes.addItem(item)
elif list == 1:
self.lista_enprogreso.addItem(item)
elif list == 2:
self.lista_completadas.addItem(item)
But when I try to save the tasks that I added from my program it doesn't save the changes:
def saveChanges (self):
db = sqlite3.connect("todo.db")
cursor = db.cursor()
date = self.calendarWidget.selectedDate().toPython()
for i in range(self.lista_pendientes.count()):
item = self.lista_pendientes.item(i)
task = item.text()
query = "UPDATE tareas SET lista = '0' WHERE tarea = ? AND fecha = ? "
row = (task, date,)
cursor.execute(query,row)
db.commit()
In this function I'm trying to save only the tasks that are in the "pendientes" list, by assigning the index 0 to those tasks, but to no avail. What could I do to save the tasks from the three QListWidgets in my database?
EDIT-SOLVED
After experimenting a bit I founded an easier solution: to use three different tables in my sqlite database for each type of task. That way I can save each task individually without worrying about the list column.

Related

Search element from SQL using Python

I am writing a python script to perform some specific task if an element ID pre-exists. I have created a database where I am saving the data elements.
I want to find out if the element link_ID exists in the database or not. How will I do that?
I have written a small script which is not perfect. The output I am getting is No such element exists.
link_ID = link_1234
sql = ''' SELECT link_ID from link_table where link_ID=? '''
var = (link_ID)
conn.execute(sql, [var])
conn.commit()
if conn.execute(sql, [var]) == True:
print("Search Successful")
flag = 1
else:
print("No such element exists")
flag = 0
You have a number of problems here. First, you should create a cursor object from your connection and use that to execute your query:
c = conn.cursor()
c.execute(sql,var)
Secondly, execute wants a tuple of values to interpolate, not a list, so do this:
var = (link_ID,)
c.execute(sql,var)
Or:
c.execute(sql,(link_ID,))
Lastly, c.execute returns the cursor object rather than the success of the query. You should fetch the result of the query using fetchone(), if your query didn't return a row then the return value of fetchone() will be None:
result = c.fetchone()
if result is not None:
print('Success:',result)
else:
print('No row found for', link_ID)

Python SQLite3 / Nested cursor.execute

Consider with this following piece of code:
for count in range(28, -1, -1):
crsr.execute("SELECT board, win1, win2 FROM positions WHERE balls = ?", (count,))
response = crsr.fetchall()
print count, len(response)
for possibility in response:
internal = possibility[0]
player = count & 1
victor = 1 - player
opponent = 2 - player
victory = possibility[opponent]
if victory:
crsr.execute("UPDATE positions SET result = ? WHERE board = ?", (victor, internal))
else:
subsequent = derive((internal, count))
for derived in subsequent:
external = reduce(derived[0])
crsr.execute("SELECT result FROM positions WHERE board = ?", (external,))
colour = crsr.fetchall()
if colour[0][0] == player:
victor = player
break
crsr.execute("UPDATE positions SET result = ? WHERE board = ?", (victor, internal))
Consider with the line:
response = crsr.fetchall()
Whenever that there are as much as 107 rows in response, the above statement returns a memory error, even on a system with 8 GB of RAM.
So, I decided that I would change with the following piece of code:
for count in range(28, -1, -1):
crsr.execute("SELECT board, win1, win2 FROM positions WHERE balls = ?", (count,))
response = crsr.fetchall()
print count, len(response)
for possibility in response:
internal = possibility[0]
to:
for count in range(28, -1, -1):
crsr.execute("SELECT COUNT(board) FROM positions WHERE balls = ?", (count,))
sum = crsr.fetchall()
total = sum[0][0]
print count, total
crsr.execute("SELECT board, win1, win2 FROM positions WHERE balls = ?", (count,))
for possibility in range(total):
response = crsr.fetchone()
internal = response[0]
Now that the line:
response = crsr.fetchone()
makes use of the crsr variable for performing with SQLite3 selection query for every iteration of possibility in range(total).
There are already other crsr statements in the same 'for' loop:
crsr.execute("UPDATE positions SET result = ? WHERE board = ?", (victor, internal))
with that statement occurring twice, and
crsr.execute("SELECT result FROM positions WHERE board = ?", (external,)).
with that statement occurring once.
So, whenever the crsr variable from the line: response = crsr.fetchall() changes with every iteration of possibility in range(total), will it not conflict with the other crsr statements already in the same 'for' loop?
We cannot create with other cursor variables for executing with different SQLite3 queries, because crsr is defined by using crsr = connection.cursor() for a specific database file, as soon as it is initialized (whichever is spline.db, in this particular case).
So, I would like to know that if there are any other alternative solutions available for it whichever are efficient enough quite directly.
A result set is part of the cursor object, so whenever you call execute(), any previous query on the same cursor object is aborted. The only way to avoid this is to use fetchall() to read all result rows before the next query is executed.
To be able to execute multiple simultaneous queries, you must use multiple cursors. Simply call connection.cursor() multiple times.
Please note that you must not modify a table that you are still reading from (even if you are using multiple cursors); changed rows might be skipped or read twice by the read cursor. If you cannot use fetchall(), put the results of the first query into a temporary table:
crsr1.execute("CREATE TEMP TABLE temp_pos(board, win1, win2)")
for count in ...:
crsr1.execute("INSERT INTO temp_pos SELECT board, win1, win2 ...")
crsr1.execute("SELECT board, win1, win2 FROM temp_pos")
for row in crsr1:
if ...:
crsr2.execute("UPDATE positions ...")
else:
crsr2.execute("SELECT ... FROM positions ...")
...
crsr1.execute("DELETE FROM temp_pos")
crsr1.execute("DROP TABLE temp_pos")

Fresh MySQL data via query using Python

I have a python script that read data from a MySQL db. There a table called ORARI and basically 3 fields: ID, acceso,spento. I need to read acceso, spento every 10 seconds. ACCESO and SPENTO are edited via a web interface, so they may vary. The problem is that when I run my script i can see the exact data from the db, but when I make a change to these values, the python script show me the initial value, not the updated value.
while True:
time.sleep(10)
dateString = strftime('%H:%M:%S')
orario = ("SELECT * FROM orari WHERE attivo = 1")
cur.execute(orario)
row = cur.fetchone()
acceso = row[1]
spento = row[2]
print acceso
print dateString
print spento
need to insert, after the query: db.commit()

Python SQLite3 Retrieve Variables From SELECT Query

I'm busy writting a python script that is querying two db tables to build a single row of data per row it finds. Here is my script at the moment
#========================================================================
# DB CONNECT FUNCTION
#========================================================================
def f_connect(status):
global gv_conn
global gv_curs
if status == 1:
gv_conn = sqlite3.connect("./data.db")
gv_curs = gv_conn.cursor()
else
gv_conn.close()
#========================================================================
# PREPARE SQL STATEMENTS
#========================================================================
def f_statements():
global users_stmt
users_stmt = ("select * from users")
global users_curs
users_curs = gv_conn.cursor()
global uinfo_stmt
uinfo_stmt = ("select * from uinfo" +
"where ui_u_id = ?")
global uinfo_curs
uinfo_curs = gv_conn.cursor()
#========================================================================
#
# MAIN SCRIPT START
#
#========================================================================
f_connect(1)
f_statements()
la_users = []
for u_row in users_curs.execute(users_stmt):
# THIS LINE GETS USERS FROM THE ABOVE STATEMENT
# AND ADDS THEM TO THE DICTIONARY
la_users.append({"u_id": u_row[0], "u_name": u_row[1]})
# THIS LINE EXECUTES ANOTHER QUERY TO RETRIEVE
# A SINGLE ROW OF DATA FROM ANOTHER TABLE
la_uinfo = uinfo_curs.execute(uinfo_stmt, "1")
f_connect(0)
My problem is that when I execute the first sql statement I can get get the data by looping using a for loop which is storing the data so i can access it using u_row[int].
When I execute the second query it is storing it inside la_uinfo although when I try to get the data from la_uinfo[int] it doesn't work? How can I retrieve the data from my second query without using another for loop? (I shouldn't have to considering it only returns one row)
Cursors are not indexable, so cursor[0] will not work. To retrieve the first row of a cursor, you should use cursor.fetchone().

Google App engine Search API Cursor not not updating

I am using cursors to get results from GAE Full text search API. The roblem is that the cursor remains same in each iteration:
cursor = search.Cursor()
files_options = search.QueryOptions(
limit=5,
cursor=cursor,
returned_fields='state'
)
files_dict = {}
query = search.Query(query_string=text_to_search, options=files_options)
index = search.Index(name='title')
while cursor != None:
results = index.search(query)
cursor = results.cursor
The cursor never become None even when the search returns only 18 results
The problem is that you getting the same 5 results over and over again. Every time you do results = index.search(query) inside your loop, you're retrieving the first five results because your query options specify a limit of 5 and empty cursor. You need to create a new query starting a the new cursor on every iteration.
cursor = search.Cursor()
index = search.Index(name='title')
while cursor != None:
options = search.QueryOptions(limit=5, cursor=cursor, returned_fields='state'))
results = index.search(search.Query(query_string=text_to_search, options=options))
cursor = results.cursor
Take a look at the introduction section of this page: https://developers.google.com/appengine/docs/python/search/queryclass

Categories

Resources