This question already has answers here:
How to print a list of tuples with no brackets in Python
(5 answers)
Closed 5 years ago.
Currently doing some selecting exercises using SQLite 3 on Python 3. This all works fine, however I want to format the output onto the shell. At the moment, when I run this program:
def select_all_products2(tech):
with sqlite3.connect('movie.db') as db:
cursor = db.cursor()
cursor.execute("select * from User where userOccupation=?",(tech,))
products2 = cursor.fetchall()
return products2
products2 = select_all_products2("technician")
print(products2)
It just prints all the matching fields out in a long, ugly list. Is there a way I can format the output onto the shell, say, with a \n after each field so it's much more easier to read?
Well yes, an SQL result set is an iterable so you can start with
for product in select_all_products2("technician"):
print (product)
Then you realize that a row is also an iterable which makes it quite possible to format the output into nice looking columns.
Related
This question already has answers here:
Variable table name in sqlite
(9 answers)
Closed 2 years ago.
So, I am new to Stackoverflow and I hope I'm writing this question well. So I'm trying to choose a table from my database (that contains 5 tables) based on user input in python. However I'm not quite sure how to do it. Here is the code:
user_input = "table1"
db.execute("SELECT number FROM (?) WHERE person = 1;")
I'm searching for a way if it is possible. Anyway any help would be appreciated.
Well, after some verifications in order to forbid SQL injections, the easiest way is to format the query string with the user input.
db.execute ("SELECT * FROM MyTable WHERE person = {};".format(user_input))
And the content of user_input would be placed on the curly brackets.
It's not very clear on how you're getting user input, though.
This question already has answers here:
Cannot return results from stored procedure using Python cursor
(3 answers)
Closed 2 years ago.
I have a Procedure that is not having OUT or IN, I don't have the permission to change the Procedure.
cursor = connection.cursor()
cursor.callproc('store_procedure',())
res = cursor.fetchall()
I tried everything but I can't get the results from MySQL Procedure.
The procedure without Python is running and return the results, it takes about 20sec but is return something.
The Procedure returns multiple rows.
Can I get the results without change the Procedure?
Use MySQLdb package for python.
Procedures are a bit more complicated, because they can return multiple resultsets
cursor.callproc('store_procedure')
for result in cursor.stored_results():
records = result.fetchall()
print(records)
Even when you retrieve only one table.
This question already has answers here:
How to create a "singleton" tuple with only one element
(4 answers)
Closed 3 years ago.
I have the following code and it works, but I need to understand why there is a comma after the variable id_to_remove, can someone explain to me why that has to be there? (I bolded the part I don't understand)
def delete_user(id_to_remove):
sql = "DELETE FROM USERS WHERE ID = ?"
conn = create_connection()
cursor = conn.cursor()
**cursor.execute(sql, (id_to_remove, ))**
conn.commit()
conn.close()
So I don't know why its id_to_remove, and not just cursor.execute(sql,(id_to_remove))
Because it will replace all the ? values with the ones in the tuple. If you don't put a comma then it is a single value, you need to add it to construct a single value tuple.
This question already has answers here:
Python sqlite3 string variable in execute
(3 answers)
Closed 4 years ago.
Basiclly I wish to use a string I have saved in a python variable as my parameter 'table-name' in "PRAGMA table_info(table-name);"
import sqlite3
connect = sqlite3.connect('exampleDB.sqlite')
cur = connect.cursor()
x = 'a string'
cur.execute("PRAGMA table_info(?)", (x,))
This was my first idea. Which did not work and neither did:
cur.execute("PRAGMA table_info(table) VALUES (?)", (x,))
Which was an idea I got from here.
Just putting the variable in there like so:
cur.execute("PRAGMA table_info(x))
also proved fruitless.
Any ideas? This is my first time posting here so feel free to lecture me on how or where I should have posted this differently should you see fit.
Try this
cur.execute("PRAGMA table_info({})".format(x))
You want to do the following:
cur.execute("PRAGMA table_info(" + x + ")")
Note, this is a duplicate of Python sqlite3 string variable in execute
This question already has an answer here:
How to get variable length placeholders in a Python call to SQLite3
(1 answer)
Closed 7 years ago.
When there are only a few parameters I can do this
cur.execute(INSERT INTO table (col1,col2) VALUES (?,?), (1,2))
but what if I have like 50 parameters? I don't want to write 50 question marks in that case. Is there a way to do something like the following?
cur.execute(INSERT INTO table (listOfColumns) VALUES tuple(['?']*len(listOfColumns)), (listOfValues))
Yes, you just build the SQL statement dynamically:
sql = ('INSERT INTO table ({}) VALUES ({})'.format(','.join(listOfColumns),
','.join('?'*len(listOfColumns))))
cur.execute(sql, listOfValues)
Note that this assumes the list of columns was generated locally and not tainted by user input. If the list of columns could be tainted you need to check it pretty carefully to ensure that it only contains valid column names before inserting it into SQL code.