How to print out SQL Statements with Python - 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())

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)

I need help using sql statements about where conditions in my Django program

This is my program. I need to change the where condition in the SQL statement to be dynamically generated using a python program because sometimes a condition in my where the statement may have no value. I do n’t want him to appear in the SQL statement when there is no value. in
Thank you very much, I really need help, I'm a newbie, I can't figure it out
#csrf_exempt
def test(request):
if request.method == "GET":
req_type = request.GET.get("get_data")
if req_type:
customer = request.GET.get('customer')
order_type = request.GET.get("orderType")
order_status = request.GET.get("orderStatus")
with connection.cursor() as cursor:
cursor.execute(
"SELECT account,order_id,start_at,update_at "
"FROM once WHERE user_id=%s OR %s='' AND order_id=%s OR %s='' AND status=%s OR %s='' ORDER BY order_id DESC ",
(customer, customer, order_type, order_type, order_status,order_status))
verify_list = dict_fetchall(cursor)
return HttpResponse(json.dumps(verify_list, cls=DecimalEncoder))
else:
with connection.cursor() as cursor:
cursor.execute('SELECT id,`name` FROM goods;')
goods_data = cursor.fetchall()
with connection.cursor() as cursor1:
cursor1.execute('SELECT id,account FROM `user`;')
user_data = cursor1.fetchall()
content = {"goods_data": goods_data, "user_data": user_data}
return render(request, 'user/test.html', content)
else:
return HttpResponseRedirect(reverse('users:login'))
if I have understood the question well, you may construct an sql query string dynamically, for example:
where = []
if customer:
where.append(f"user_id={customer}") # assuming customer is integer, put value without quotes
if order_type:
where.append(f"order_id={order_type}") # assuming order_type is integer, put value without quotes
if order_status:
where.append(f"status='{order_status}'") # assuming order_status is string, put value inside quotes
where = ' AND '.join(where)
where = ('WHERE ' if where else '') + where
query = f"SELECT account, order_id, start_at, update_at FROM once {where} ORDER BY order_id DESC"
with connection.cursor() as cursor:
cursor.execute(query)

converting to string from sqlite tuple

When I retrieve data from my database, it is returned in the following format however I need it simply as just the text on its own:
[(u'milk',)]
[(7,)]
i have tried converting it into a string etc so that I could use a for loop to iterate through it and pop off the unneeded characters but nothing has worked
Here is my code:
def retShopping(db):
item = []
quan = []
with sqlite3.connect(db) as db:
cursor = db.cursor()
cursor.execute('''SELECT quantity FROM Shopping''')
hold = str(cursor.fetchall())
quan.append(hold)
cursor.execute('''SELECT item FROM Shopping''')
hold2 = str(cursor.fetchall())
item.append(hold2)
print(item[0])
print(quan[0])
I am hoping to be able to just end up with the strings'milk' and '7' so that I am able to use them in print statements.
try this:
def retShopping(db):
with sqlite3.connect(db) as db:
cursor = db.cursor()
cursor.execute('''SELECT quantity FROM Shopping''')
hold = cursor.fetchall()
print(hold[0][0])
cursor.execute('''SELECT item FROM Shopping''')
hold2 = cursor.fetchall()
print(hold2[0][0])

Can i store a cursor.fetchone() in a variable

Hell guys just jumped in to python and i'm having a hard time figuring this out
I have 2 queries . . query1 and query2 now how can i tell
row = cursor.fetchone() that i am refering to query1 and not query2
cursor = conn.cursor()
query1 = cursor.execute("select * FROM spam")
query2 = cursor.execute("select * FROM eggs")
row = cursor.fetchone ()
thanks guys
Once you perform the second query, the results from the first are gone. (The return value of execute isn't useful.) The correct way to work with two queries simultaneously is to have two cursors:
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select * FROM spam")
cursor2.execute("select * FROM eggs")
cursor1.fetchone() #first result from query 1
cursor2.fetchone() #first result from query 2
It doesn't. The return value from cursor.execute is meaningless. Per PEP 249:
.execute(operation[,parameters])
Prepare and execute a database operation (query or
command)...
[...]
Return values are not defined.
You can't do it the way you're trying to. Do something like this instead:
cursor = conn.cursor()
cursor.execute("select * FROM spam")
results1 = cursor.fetchall()
cursor.execute("select * FROM eggs")
if results1 is not None and len(results1) > 0:
print "First row from query1: ", results1[0]
row = cursor.fetchone()
if row is not None:
print "First row from query2: ", row

How to get field names when running plain sql query in django

In one of my django views I query database using plain sql (not orm) and return results.
sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
I am getting the data fine, but not the column names. How can I get the field names of the result set that is returned?
On the Django docs, there's a pretty simple method provided (which does indeed use cursor.description, as Ignacio answered).
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
According to PEP 249, you can try using cursor.description, but this is not entirely reliable.
I have found a nice solution in Doug Hellmann's blog:
http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html
from itertools import *
from django.db import connection
def query_to_dicts(query_string, *query_args):
"""Run a simple query and produce a generator
that returns the results as a bunch of dictionaries
with keys for the column values selected.
"""
cursor = connection.cursor()
cursor.execute(query_string, query_args)
col_names = [desc[0] for desc in cursor.description]
while True:
row = cursor.fetchone()
if row is None:
break
row_dict = dict(izip(col_names, row))
yield row_dict
return
Example usage:
row_dicts = query_to_dicts("""select * from table""")
try the following code :
def read_data(db_name,tbl_name):
details = sfconfig_1.dbdetails
connect_string = 'DRIVER=ODBC Driver 17 for SQL Server;SERVER={server}; DATABASE={database};UID={username}\
;PWD={password};Encrypt=YES;TrustServerCertificate=YES'.format(**details)
connection = pyodbc.connect(connect_string)#connecting to the server
print("connencted to db")
# query syntax
query = 'select top 100 * from '+'[{}].[dbo].[{}]'.format(db_name,tbl_name) + ' t where t.chargeid ='+ "'622102*3'"+';'
#print(query,"\n")
df = pd.read_sql_query(query,con=connection)
print(df.iloc[0])
return "connected to db...................."

Categories