How can I use a specified variable in a SELECT SQL statement? - python

I am creating a program that will allow a user to pick 2 chemical elements from menus and then tell them the result of the reaction between those two. I know my database is working, and I am trying to create two variables that can be changed at any point in the program. This is the code I have so far, using 2 values that I know the correct outcome for:
import sqlite3
conn = sqlite3.connect('Experiment_simulator_database.db')
c = conn.cursor()
firstchoice = 1
secondchoice = 36
sqlcommand = "SELECT Outcome_ID FROM Reactions WHERE Choice_1 = firstchoice AND Choice_2 = secondchoice"
c.execute(sqlcommand)
result = c.fetchone()
print(result)
How can I get firstchoice and secondchoice in the select statement to take on the values I specified above?

You can have placeholders in your sql and bind the values when you call execute
sqlcommand = "SELECT Outcome_ID FROM Reactions WHERE Choice_1 = ? AND Choice_2 = ?"
c.execute(sqlcommand, (firstchoice, secondchoice,))

You can pass these variables in parameter where you are using.
firstchoice = 1
secondchoice = 36
sqlcommand = "SELECT Outcome_ID FROM Reactions WHERE Choice_1 = " + firstchoice + "AND Choice_2 = " + secondchoice "
c.execute(sqlcommand, firstchoice, secondchoice)

Related

Python SQLite printing from a table where ID is equal set variable

This code gets the category from users input in film_list table and gets IDs of all the movies with that category:
kategorija=input("Enter the category: ")
c.execute("SELECT DISTINCT FID FROM film_list WHERE category=?", (kategorija,))
filmid = c.fetchall()
print(filmid)
I'm trying to get a name and the release year of the film with the ID that we got in a previous code fragment.
result = []
for a in filmid:
c.execute("SELECT title,release_year FROM film WHERE film_id = 'a'")
result.append(c.fetchone())
print(result)
When I enter any number, for example 1, it returns what I need, so I suppose there's something wrong in the declaration of film_id, but I don't know how I can solve this.
Full code:
import sqlite3
#Connectin to DB
conn = sqlite3.connect('sakila.db')
c = conn.cursor()
#Checking if the connection to the DB is successful
if (conn):
print("Connection successful")
else:
print ("Connection unsuccessful")
kategorija=input("Enter the category: ")
c.execute("SELECT DISTINCT FID FROM film_list WHERE category=?", (kategorija,))
filmid = c.fetchall()
print(filmid)
result = []
for a in filmid:
c.execute("SELECT title,release_year FROM film WHERE film_id = 'a'")
result.append(c.fetchone())
print(result)
You may use the following single query:
SELECT f.title, f.release_year
FROM film f
INNER JOIN film_list fl ON fl.fid = f.film_id
WHERE fl.category = ?
Your updated Python code:
sql = '''SELECT f.title, f.release_year
FROM film f
INNER JOIN film_list fl ON fl.fid = f.film_id
WHERE fl.category = ?'''
kategorija = input("Enter the category: ")
result = []
c.execute(sql, (kategorija,))
result.append(c.fetchAll())
print(result)

Python/MySQL - Fetching only 5 lines of the query and if user presses a letter it shows next 5 lines and so on

Working on a python app connecting to a movies database in mysql:
Looking to show first 5 lines from the query, if the user presses anything besides from q(will bring back to main menu) it will fetch next 5 lines and so on. So far I have :
with conn:
cursor = conn.cursor()
query = "select FilmName,ActorName from Film,Actor,FilmCast where Film.FilmID = FilmCast.CastFilmID and FilmCast.CastActorID = Actor.ActorID order by FilmName ASC,ActorName ASC LIMIT 5;"
cursor.execute(query)
result = cursor.fetchall()
print(result)
button = str(input('Press Q to quit'))
if button == 'q':
main()
Any ideas?
In that case you want to use the concept of OFFSET.
Use a counter variable to keep track of your row number on each user input, and the use that in your query.
Here's the code
offset = 0
with conn:
cursor = conn.cursor()
limit = 5
query = """select FilmName,ActorName from Film,Actor,FilmCast
where Film.FilmID = FilmCast.CastFilmID
and FilmCast.CastActorID = Actor.ActorID
order by FilmName ASC,
ActorName ASC LIMIT {0}, {1};""".format(offset, limit)
cursor.execute(query)
result = cursor.fetchall()
print(result)
button = str(input('Press Q to quit'))
if button == 'q':
main()
else:
offset += 1

How to use a variable in where clause in python to access sql

u=int(input(' ENTER YOUR CHOICE(1-6) : '))
sql_select_Query = 'select * from hotel **where H_ID =u'**
mycur.execute (sql_select_Query)
dip=mycur.fetchall()
for x in dip:
print(x,'\n')
getting error as
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'u' in 'where clause'
Doing from PYTHON
u is the input from user. how to include it in where clause of sql
You need to use a placeholder in the query (for MySQL that's usually %s) and then pass the variable separately to .execute():
u = int(input(' ENTER YOUR CHOICE(1-6) : '))
sql_select_Query = 'select * from hotel where H_ID = %s'
mycur.execute(sql_select_Query, (u,))
dip = mycur.fetchall()
for x in dip:
print(x, '\n')
The easiest way for me is put a f before the string quotes, like
f"the result is {your_variable}"
in code editor
unfortunately this just works in >= python3.7. But you can also use .format.
"the result is {your_variable}".format(your_variable=0)
in code editor
Your script would be
sql_select_Query = f'select * from hotel where H_ID = {u}'
or
sql_select_Query = 'select * from hotel where H_ID = {u}'.format(u=u)

How to use place holders in tkinter sqlite

I have a program with a sqlite database and I'm trying to update a record by using place holders. I'm not sure why but I'm getting the following error: TypeError: function takes at most 2 arguments (3 given)
So here is a sample of my code if anyone can figure out what I'm doing wrong.
conn = sqlite3.connect('roominventory.db')
c = conn.cursor()
c.execute("SELECT * FROM rooms")
records = c.fetchall()
for record in records:
if record[0] == roomget:
break
t = ("N",)
rm = (roomget,)
c.execute("UPDATE rooms SET vacant = ? WHERE number = ?", t, rm)
c.fetchall()
conn.commit()
conn.close()
You should use tuple:
t = "N"
rm = roomget
c.execute("UPDATE rooms SET vacant = ? WHERE number = ?", (t, rm))
# c.fetchall() # should not call it here
conn.commit()
conn.close()
In your update query, I think if you do like this it should work.
t = "N"
rm = roomget
query = "UPDATE rooms SET vacant = ? WHERE number = ?", (t, rm)
c.execute(*query)
# c.fetchall() # should not call it here
conn.commit()
conn.close()
This is because of at the time of executing query it will be parsed and need to unpack the tuple. Let me know if works.

Read things out of database WHERE 'id'=

I am trying to build an examine (Dutch = overhoor) program in Python. Here's my code:
cursor = cnx.cursor()
willekeurig = random.randint(0,9)
query = ('SELECT FRwoord, NLwoord FROM unite8app1 WHERE "id"=willekeurig')
cursor.execute(query)
for (NLwoord, FRwoord) in cursor:
print("Wat is de vertaling van: " + FRwoord + "?")
vertaling = input()
if vertaling == NLwoord:
print("Well done")
else:
print("Helaas")
for (FRwoord, NLwoord) in cursor:
print(FRwoord,NLwoord)
print(query)
cnx.close
I am trying to get a random question based upon the id of that question in my database. I tried some alternatives like:
WHERE 'id'=1
WHERE 'ID'=1
etc
But it doesn't want to work if I run my program (after pressing enter) it says that NLwoord and FRwoord aren't defined, but when I remove that bit of code it works just fine. (if I have just 1 item in my database)
My question is how to grab a random id from my database? I have included some pictures of the database.
http://updo.nl/file/37e39c15.JPG
http://updo.nl/file/1de64d64.JPG
Right now you are not passing the value of willekeurig, but the text willekeurig. Try these two lines for your query & execute insted:
query = "SELECT FRwoord, NLwoord FROM unite8app1 WHERE id=%s"
cursor.execute(query, (willekeurig,))
Have you tried this without any quotes around id?
You should also be able to use:
SELECT FRwoord, NLwoord FROM unite8app1 ORDER BY RAND() LIMIT 1

Categories