How do you display information from a database in python? - python

I am new to Python and I am trying to make a flashcard script that retrieves the keyword and the definition from a database and then displays both on a flashcard using pyqt.
Does anyone know how to do this because I am having real trouble figuring it out.
So far, I have some pseudo code below.
Function loadFlashcards(topic)
Import sqlite3
With sqlite3.connect (‘db_flashcards’) as db:
Cursor = db.cursor()
Sql = ‘SELECT * FROM tbl_flashcards’;
Cursor.execute(sql)
Result = cursor.fetchall()
for row in result:
print(“Defintion:” + str(row[2]
flip = input(“Press 1 to flip”)
if flip == “1”:
then print (“Keyword: +str[3])
else:
print(“Error”)
END for

Related

SQLite query difficulty

I have a SQLite db with three relational tables. I'm trying to return the max record from a log table along with related columns from the other tables based on the ID relationships.
I created the query in DB Browser and verified it returns the expected record however, when I use the exact same query statement in my python code it never steps into the 'for' loop.
SQL statement in python -
def GetLastLogEntry():
readings = ()
conn = sqlite3.connect(dbName)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT f.FoodCategory, f.FoodName, gs.FoodWeight,
gsl.GrillDateTime, gsl.CurrentGrillTemp, gsl.TargetGrillTemp,
gsl.CurrentFoodTemp, gsl.TargetFoodTemp, gsl.CurrentOutsideTemp,
gsl.CurrentOutsideHumidity FROM Food as f, GrillSession as gs,
GrillSessionLog as gsl WHERE f.FoodId = gs.FoodId AND
gs.GrillSessionID = gsl.GrillSessionID AND gsl.GrillSessionLogID =
(SELECT MAX(GrillSessionLog.GrillSessionLogID) FROM
GrillSessionLog, GrillSession WHERE GrillSessionLog.GrillSessionID
= GrillSession.GrillSessionID AND GrillSession.ActiveSession =
1)")
for row in cursor:
print("In for loop")
readings = readings + (row['FoodCategory'], row['FoodName'])
print("Food Cat = " + row['FoodCategory'])
cursor.close()
return readings
The query in DB Browser returns only one row which is what I'm trying to have happen in the python code.
Just discovered the issue....
Using DB Browser, I updated a record I'm using for testing but failed to "write" the change to the database table. As a result, every time I was executing my python code against the table it was executing the query with the original record values because my change wasn't yet committed via DB Browser.
Huge brain fart on that one.... Hopefully it will be a lesson learned for someone else in the future.

How can I enter data into database by pressing the button with using python?

I'm setting up a project by using python language to take feedback from customers by pressing the button, my question about the code to enter the data into the database?
import mysql.connector
connector = mysql.connector.connect(host="host", user="user", passwd="password", database="DB")
cnx = connector.cursor()
cnx.execute("INSERT INTO ... VALUES (%s)", ('data'))
# Or execute a query just as always
#cnx.execute("INSERT INTO ... VALUES (...)")
connector.commit()
# If "SELECT * FROM ..." use next line to get the data
#result = cnx.fetchall()
cnx.close()
connector.close()

How to include external python file i SQL request

I'm not experienced in Python.
I have the following Python code:
How can i import various values from files outside the file, and use them in a SQL request?
#!/usr/bin/env python
import MySQLdb
import Stamdata
from Stamdata import Varmekurve
K = Varmekurve
print K #this vorks, and the value 1.5 from Varmekurve is printed.
#Open database connection
db = MySQLdb.connect("localhost","root","Codename","MyDvoDb")
#prepare a cursor object using cursor method
cursor = db.cursor()
#Get SetTemp FROM SQL
sql = ("SELECT SetTemp FROM varmekurver WHERE kurvenummer = '1.5' AND TempSensor ='15'")
#Here i would like to import the value from Varmekurve instead of '1.5', and the data from a DS18b20 temp. sensor instead of '15'.
#The DS18B20 sensor are located in '/sys/bus/w1/devices/28-0316007914ff/w1_slave'
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print row[0]
db.close()
Only the Stamdata file are in the same library.
The Script shall control a motorvalve by calling the SetTemp and open/close a mix-valve if the temp. is to high or low (within 2-3 degrees)
But i haven't come that far yet :0)
to dynamically change the value in the string from a variable do:
SELECT SetTemp FROM varmekurver WHERE kurvenummer = '{}' AND TempSensor ='{}'.format(val1, val2)
If you want to import these values from an external source, like a flat file, you can do it in a number of ways. For example using Pandas.

SQL and Python - using a variable in an SQL statement

import sqlite3
conn = sqlite3.connect('troubleshooting.db')
cur = conn.cursor()
user = input("hello")
for row in cur.execute('SELECT user FROM problems WHERE user = %s'):
print(row)
My problem here is that the variable 'user' is only being read as text and not changing occurring to what I name it (user = input("hello")). How do I change it so it does read it as a variable (please keep it simple, I am a beginner when it comes to programming).
Thanks for helping out :)

Can't display sqlite3 data on python

I want to display a specific column from sqlite3 on a python Tkinter combobox, but what's displayed instead is <sqlite3.Cursor object at 0x0000000003E73110>, I don't know what to do? I just started coding not a while ago.
I write the following:
from tkinter import *
from tkinter import ttk
import sqlite3
conn = sqlite3.connect('Library.db')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS tablename (Name TEXT UNIQUE NOT NULL)")
combolist = c.execute("SELECT Name FROM tablename")
root = Tk()
ttk.Combobox(root, value = (combolist))
Calling execute on a cursor object won't return you the values. Instead you can iterate over the cursor, or call c.fetchall() to get all of the results back together.
sqlite3 also supports a shorthand where you can call conn.execute(...) and get back the results directly without using an explicit cursor at all, but that requires you to call execute on the connection rather than the cursor.
Also you may want to unpack the name field out of each row.
I think this code should work (though I haven't tested it):
conn = sqlite3.connect('Library.db')
with conn:
conn.execute("CREATE TABLE IF NOT EXISTS tablename (Name TEXT UNIQUE NOT NULL)")
... more code that actually inserts some data is assumed here ...
with conn:
combolist = [row["name"] for row in conn.execute("SELECT Name FROM tablename"))]

Categories