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

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)

Related

How to print out SQL Statements with Python

I have declared Variables that i got from tkinter Entrys and I work with MySql connector. Now I want to know how to make a SQL Statement and print it out. Thats what I have know:
def suche():
isbn = ISBNE.get()
vnr = VNRE.get()
titel = TitelE.get()
Genre = GenreE.get()
autorvor = AutorE.get()
#cursor.execute("SELECT * FROM bücher WHERE titel LIKE \""+titel+"\" AND
#AutorVorname LIKE \""+autorvor+"\" AND isbn LIKE\""+isbn+"\"")
cursor.execute("SELECT * FROM bücher WHERE titel LIKE '%s'" % titel)
row = cursor.fetchone()
while row!=None:
print(row)
row = cursor.fetchone()
print(isbn)
but this doesn't work for me
You should not use simple string formatting to construct a SQL query string. Use a parametrized query instead:
cursor.execute("SELECT * FROM bücher WHERE titel LIKE %s" , (titel,))
See the dokumentation for it here
The reason behind this is SQL-Injection, a funny explanation can be found here: https://xkcd.com/327/ . Sql injection is dangerous and can lead to damage on your database.
row-based fetching and printing data is described here:
# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
print(row)
row = cursor.fetchone()
Untested pseudo code:
You can extract your isbn, vnr, title, genre out of each row and store them elsewise - or copy it into your own data structs:
def Book:
def __init__(self, isbn,name,vnr,genre):
self.isbn = isbn
self.name = name
self.vnr = vnr
self.genre = genre
def Suche(title):
books = []
cursor.execute("SELECT isbn,name,vnr,genre FROM bücher WHERE titel LIKE %s", (titel,))
row = cursor.fetchone()
while row is not None:
isbn,name,vnr,genre = row
books.append(Book(isbn,name,vnr,genre))
row = cursor.fetchone()
print(books)
return books
# call as:
books = Suche(TitelE.get())

python to write data into table error

write python program to create a mysql table and insert data into this table,the program is as follows:
def pre_data_db_manage(type,data):
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="********", db="facebook_info",charset="utf8")
cur = conn.cursor()
if type == "pre_davi_group_members_data":
is_exist_table_sql = "SHOW TABLES LIKE 'fb_pre_davi_group_members_posts'"
if cur.execute(is_exist_table_sql) == 0:
create_table_sql = '''CREATE TABLE fb_pre_davi_group_members_posts (id bigint not null primary key auto_increment,userID bigint,userName varchar(128),userURL varchar(256),
postTime varchar(128),postText text,postTextLength int,likesCount int,sharesCount int,commentsCount int,postTextPolarity varchar(64),postTextSubjectivity varchar(64))'''
cur.execute(create_table_sql)
r = re.compile(r'^[a-zA-Z0-9]')
for item in data:
if "'" in item["PostText"]:
item["PostText"] = item["PostText"].replace("'"," ")
if "\\" in item["PostText"]:
item["PostText"] = item["PostText"].replace("\\","\\\\")
for i in item["PostText"]:
result = r.match(i)
if result == None:
print("in re")
item['PostText'] = item['PostText'].replace(i, ' ')
if "nan" in item["SharesCount"]:
item["SharesCount"] = 0
if "nan" in item["LikesCount"]:
item["LikesCount"] = 0
if "nan" in item["CommentsCount"]:
item["CommentsCount"] = 0
if "nan" in item["PostTextLength"]:
item["PostTextLength"] = 0
item["PostTextLength"] = int(item["PostTextLength"])
item["LikesCount"] = int(item["LikesCount"])
item["SharesCount"] = int(item["SharesCount"])
item["CommentsCount"] = int(item["CommentsCount"])
if type == "pre_davi_group_members_data":
insert_sql = '''INSERT INTO fb_pre_davi_group_members_posts (userID,userName,userURL,
postTime,postText,postTextLength,likesCount,sharesCount,commentsCount,postTextPolarity,postTextSubjectivity) VALUES
({0},"{1}",'{2}','{3}','{4}',{5},{6},{7},{8},{9},{10})'''.format(item["UserID"],item["UserName"],item["UserURL"],item["PostTime"],item["PostText"],item["PostTextLength"],item["LikesCount"],item["SharesCount"],item["CommentsCount"],item["PostTextPolarity"],item["PostTextSubjectivity"])
print(insert_sql)
try:
cur.execute(insert_sql)
except Exception as e:
print("insert error")
continue
cur.close()
conn.commit()
conn.close()
and write call statement as follows:
type = "pre_davi_group_members_data"
pre_data_db_manage(type, df_list)
however,when execute this program, found that no data have been inserted into table:fb_pre_davi_group_members_posts,
in the mysql order line, write:
select count(*) from fb_pre_davi_group_members_posts;
the result is 0
could you please tell me the reason and how to solve it

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

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)

Use a query in sqlite value - python

Does anyone know how to execute a query inside a value in python sqlite
The eroor i am getting is:
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
my code is here:
Name = input("Enter the name of the product you want to purchase: >>")
item = Name
qty = input("Enter the Quantity of the product you want to purchase: >>")
today = date.today()
cursor = db.cursor()
cursor.execute("SELECT CatID from Products where Name=?",(Name,))
result = cursor.fetchall()
confirm = input("are you sure you want tot buy this product (y/n): >>" )
if confirm == "y":
### In this query where it says result i want to execute the data from the result query
cursor.execute("INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) Values(?,?,?,?,?)",(Username,result,today,qty,Name))
db.commit()
print("Product purchased. Thankyou for your order")
cursor.execute("UPDATE Products SET Qty = (? -1) where Name = ?",(qty,item,))
else:
print("The program will now terminate")
You can also iterate over result:
for row in result:
cursor.execute(
"INSERT INTO OrderHistory(Username,Category,Date,Qty,ItemHistory) SELECT CatID,?,?,?,? FROM Products WHERE Name=?",(Username,row,today,qty,Name))
db.commit()

Python sqlite loop thought all tables in database

I have 700 tables in a test.db file, and was wondering how do I loop through all these tables and return the table name if columnA value is -?
connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"')
How do I put all 700 tables in all_tables?
To continue on a theme:
import sqlite3
try:
conn = sqlite3.connect('/home/rolf/my.db')
except sqlite3.Error as e:
print('Db Not found', str(e))
db_list = []
mycursor = conn.cursor()
for db_name in mycursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'"):
db_list.append(db_name)
for x in db_list:
print "Searching",x[0]
try:
mycursor.execute('SELECT * FROM '+x[0]+' WHERE columnA" = "-"')
stats = mycursor.fetchall()
for stat in stats:
print stat, "found in ", x
except sqlite3.Error as e:
continue
conn.close()
SQLite
get all tables name:
SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;
Cycle
for table in tables:
...
connection.execute('SELECT * FROM "table1" WHERE "columnA" = "-"')
or one SQL request UNION
sql = []
for table in tables
sql.append('(SELECT * FROM "' + table + '" WHERE "columnA" = "-";)')
' UNION '.join(sql)
You could query the sqlite_master to get all the table names within your database: SELECT name FROM sqlite_master WHERE type = 'table'
sqlite_master can be thought of as a table that contains information about your databases (metadata).
A quick but most likely inefficient way (because it will be running 700 queries with 700 separate resultsets) to get the list of table names, loop through those tables and return data where columnA = "-":
for row in connection.execute('SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name').fetchall()
for result in connection.execute('SELECT * FROM ' + row[1] + ' WHERE "columnA" = "-"').fetchall()
# do something with results
Note: Above code is untested but gives you an idea on how to approach this.

Categories