python sqlite3 selecting variables - python

I'm trying to select 3 variables in a sqlite3 statement. And putting this into 3 python variables, can't get it to work..
knifekingdb.execute("SELECT rank, rounds, date FROM knifekingdb WHERE steamid = ?", steamid)
I can put it into one list by assigning that statement to a python variabel. But i don't know how to split a list of integers and strings into different variabels.
Can you please help me, because i'm a bit stuck.

knifekingdb.execute(
"""SELECT rank, rounds, date
FROM knifekingdb WHERE steamid = ? LIMIT 1""", steamid)
try:
rank, rounds, date = knifekingdb.fetchone()
except TypeError:
# fetchone returned None because no row was found
# handle error here
raise

Related

SQLite3 - How can I assign Variables from the data returned from a SQL Query?

I'm a total Noob and don't know how I can assign variables to the data returned from a SQL Query so that I can then manipulate it. The example below captures random data and not the results from the SQL Query.
I'm using the Replit website with sqlite3.
connect_SQL.execute(""" SELECT MAX(last),exchange from MY_TABLE WHERE base="XRP" and target="EUR" """)
Sell_on=connect_SQL.fetchall()
Sell_price=last_price
Sell_exchange=exchange
print ("A: ", Sell_price , " B: ", Sell_exchange) # This doesnt work wrong value
Print (Sell_on) # give output like [(0.3786567, 'EXMO') but I can assign variables to the price/exchange
All Help is appreciated!
The Price and Exchange details contained in Sell_on are correct, but combined into one output [(0.3786567, 'EXMO') I want to break this down and assign to two different variables, assigning one to the price (0.3786567) and the other to the exchange ('EXMO').

Comparing SQL results with Python

I was looking for a way to my program to take 2 values from my database, compare them and update or insert some value.
I tried in sqlite3 but I didn't find a good solution and I tried on python, but when I run the program, the values are different and never match. I already look on google, here on stack overflow, but didn't find anything.
cursor.execute("select * from [Sistema]")
Teste = cursor.fetchall()
cursor.execute("select [SistemaOperacional] from [Sistema] where [SistemaOperacional] = 'teste'")
comparacao = cursor.fetchall()
testando = comparacao
for row in Teste:
#I was checking the values to see if they where equal
print(comparação[0]) #Value ('teste',)
print(row[0]) #Value 'teste'
if row[0] == comparação[0]:
cursor.execute("Update [Sistema] set [SistemaOperacional] = '1' where [VersaoBanco] = 3")
print('Executado')
break
else:
cursor.execute("insert into [Sistema] values ('9','9','1')")
print('não')
break
the output whas
('teste',)
teste
não
I wasn't finding a solution for this in sql, that's why I tried with python, but I'm open to listen any other suggestion than python
It's a pretty common problem for people unfamiliar with Python/MySQL to run into troubles receiving tuples back from querying. comparacao[0] is a tuple. Tuples are compared lexicographically by element, so you'd have to retrieve the first element (like #Gwyn Evans said) e.g. comparação[0][0] in order to compare it to your string row.
Here is a link to Python docs about comparisons: https://docs.python.org/2.0/ref/comparisons.html
I could be on the wrong track here, but isn't your comparação[0] itself a tuple, so you probably want to be comparing comparação[0][0] with row[0].

ValueError: invalid literal for int() with base 10: 'NewFilmLikes' in Python

I am trying to get a value from an SQLite3 database and put that into a variable called FilmLikes, I then want to add one to it and I store that in the variable NewFilmLikes. I then try to change the value of this box in my database to the 'NewFilmLikes', however I always get this problem:
ValueError: invalid literal for int() with base 10: 'NewFilmLikes'
Here is the code showing that:
FilmLikes=i[2]
NewFilmLikes=(int(FilmLikes))+1
filmUpdate=("UPDATE HORRORALL SET likes = ? WHERE number = 1"(NewFilmLikes))
c.execute(filmUpdate)
conn.commit()
Here is the code for i:
for i in find_film:
print('')
print('Number',(i[0]))
print(i[1])
filmChoice=int(input('Please choose which number you would like to like: '))
if filmChoice==1:
find_film=c.execute("SELECT * FROM HORRORALL")
for i in find_film:
if i[0]==filmChoice:
## FilmLikes=i[2]
try:
x=(int(i[2]))+1
except:
pass
## FilmLikes=i[2]
## NewFilmLikes=(int(str(FilmLikes)))+1
filmUpdate=("UPDATE HORRORALL SET likes = ? WHERE number = 1"(x))
c.execute(filmUpdate)
conn.commit()
Without knowing much more about your setup, it's hard to answer this properly.
Mind you, the specific error you refer to (ValueError: invalid literal for int() with base 10: 'NewFilmLikes') often occurs when you get a decimal rather than an integer.
Here's a sort of general answer.
It's good practice not to use SELECT * because it hides what you are trying to retrieve. Specify, e.g SELECT film_id, file_name, no_of_likes FROM horrorall as this way you can see what you are retrieving and the positions.
You're retrieving the entire list of films with find_film and then looping through to find which one. SQL has a find function, it's called WHERE and you are using it in the film_update section. If you have the ID or Name inputted by the user, you can then call only the record you need. E.g. "SELECT film_id, file_name, no_of_likes FROM horrorall WHERE film_id = ?" (filmChoice,)
Note that parameterised queries use a tuple, even if there is only one parameter - hence it is (filmChoice,) with a comma (and for filmUpdate you would need (x,))
filmUpdate will only ever update the first film. I assume that because your if ... loop continues through all the possible options? You can shortly this by putting another ? in there for your WHERE e.g. filmUpdate=("UPDATE HORRORALL SET likes = ? WHERE number = ?"(x,i[0]))
How does the user know what film to select? You aren't retrieving the list until they give you a number!
Putting all of this together, here is an example. Note this is far from the ideal way of doing it, I don't want to throw too many ideas at you in one go!
# Get the whole list of films to show to the user
find_film = c.execute("SELECT film_id, film_name FROM HORRORALL")
# Present the list for selection
for films in find_film:
print(str(films[0]) + '. ' + films[1])
# Get the users input as an integer
filmChoice = int(input('Please choose which number you would like to like: '))
# Fetch the number of likes of the selected film
film_likes = c.execute('SELECT likes FROM HORRORALL WHERE film_id = ?' (filmChoice,))
# Send the update back to the database
c.execute("UPDATE HORRORALL SET likes = ? WHERE film_id = ?"(int(film_likes[0]) + 1, filmChoice)
conn.commit()

How do I iterate over a SQLite database using the Python API?

Basically I want to be able to choose an amount of numbers using for x...in range(y amount of numbers) and inject them into an SQLite database. However I receive the following error:
line 17, in <module>
values (?)""") (number)
sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses 1, and there are 0 supplied.
Here is my non functioning code. All input is appreciated.:
import sqlite3
conn = sqlite3.connect("usernames.sqlite")
c = conn.cursor()
c.execute('''create table numbers (number)''')
for number in range(21):
# Insert a row of data
c.execute("""insert into numbers
values (?)"""),(number)
# Save (commit) the changes
conn.commit()
# We can also close the cursor if we are done with it
c.close()
execute takes a tuple of values in the case of "?" parameters, so you need to write:
c.execute("""insert into numbers values (?)""", (number,))
(number,) is a way to define a tuple with one element.
And by the way, you can do this more efficiently using the executemany method:
c.executemany(
"""insert into numbers values (?)""",
[(number,) for number in range(21)]
)
You've got a misplaced closed paren in values (?)"""),(number).
Not sure why this wasn't a syntax error, though. Is this the exact code that you were using?

Python SQL select row from specific variable field

I'd like to grab a specific value from a row based on a random variable. Here's an example table the PID column is an "auto-increment primary key integer" and the other 2 columns are TEXT
example-table
PID NAME PHONE
--- ---- -----
1 bill 999-9999
2 joe 888-8888
I'd like to throw a random variable at the table
randomVariable = raw_input('Enter something: ')
> 1
and have the code return the name
> bill
I know I can use something like...
randomVariable = raw_input('Enter something: ')
sql = ("SELECT name FROM example_table WHERE pid='%s'" % randomVariable)
result = cursor.execute(sql)
print result
> bill
Apparently using '%s' isn't secure and it is suggested to use '?' in it's place.
randomVariable = raw_input('Enter something: ')
sql = ("SELECT name FROM example_table WHERE pid=?", randomVariable)
result = cursor.execute(sql)
print result
But this doesn't seem to work for me. I end up with...
"ValueError: operation parameter must be str or unicode"
I realize I could just grab all the rows and put them into a variable which I could then iterate over till I find what I'm looking for but I'm thinking that wouldn't be very efficient with a large database. can anyone help point me in the right direction with this?
I believe you're meant to use it like this
randomVariable = raw_input('Enter something: ')
sql = "SELECT name FROM example_table WHERE pid=?"
result = cursor.execute(sql, randomVariable)
print result
Validate the user input, and %s is fine. Storing your rows and putting them into a list is not a good idea at all, since the amount of rows will grow over time, taking up a huge amount of memory when not even in use. To guard against SQL injection, you could validate input using something like a typecast to an int, put that in a try/except block, and this would stop all malicious input such as ' OR 1=1--

Categories