Python - MySQLdb parametrized query - python

I'm trying to create a simple script for changing some mysql data, but I'm little bit confused about parametrized queries. The code look like this:
reader_id = sys.argv[1]
cmd_id = sys.argv[2]
conn = mysql.connect(user='...', passwd='...', host='...', db='...')
curs = conn.cursor()
mysql_data = {
"reader_id": int(reader_id),
"cmd_id": int(cmd_id)
}
curs.execute("UPDATE `reader_config_hw` SET `changed_` = '1' "
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
curs.execute("UPDATE `reader` SET `check_for_command` = '1' WHERE `id` = %(reader_id)d", mysql_data)
and the error result is
Traceback (most recent call last):
File "./main.py", line 25, in <module>
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
File "/usr/lib64/python3.6/site-packages/MySQLdb/cursors.py", line 210, in execute
query = query % args
TypeError: %d format: a number is required, not str
It says that number is required but I already changed the type of the variable by int(reader_id), is it right?

Try changing
"WHERE 'object_id' = %(reader_id)d AND 'id' = %(cmd_id)d;"
to
"WHERE 'object_id' = %(reader_id)s AND 'id' = %(cmd_id)s;"
I think the 'd' after your variable calls indicates a "digit" whereas you need to use a string.
EDIT: to clarify, strings can be used in place of integers in MySQL queries

Related

Run code inside a string with python .format

I need to use code saved in a string (tmp_str) inside .format ?
tmp_str="ID='ID_VAR_DICT'"
sql_text="SELECT FIELD FROM TABLE_A WHERE ID = {ID}"
sql_query = sql_text.format(ID='ID_VAR_DICT')
print ('sql_query -->',sql_query) #Print A
sql_query = sql_text.format(eval(tmp_str))
print ('sql_query -->',sql_query) #Print B
Basically I need #Print B to output the same as #Print A but passing the contents off tmp_str to .format
Output:
('sql_query -->', 'SELECT FIELD FROM TABLE_A WHERE ID = ID_VAR_DICT')
Traceback (most recent call last):
File "_testes.py", line 7, in <module>
sql_query = sql_text.format(eval(tmp_str))
File "<string>", line 1
ID='ID_VAR_DICT'
Thanks in advance,
M
This isn't a recommendation -- as chepner says in a comment, you should use a prepared statement with parameters.
But if you really need to do it your way, you have to eval the entire expression, not just the argument.
sql_query = eval(f'sql_text.format({tmp_str})')

Executing python function in postgres

I'm trying to run a python function on the cursor.execute parameter but it just throws me this error.
I'm using psycopg2
Traceback (most recent call last):
File "cliente.py", line 55, in <module>
cursorDB.execute(get_datos_animal('falsa'))
psycopg2.errors.UndefinedColumn: column "falsa" does not exist
LINE 1: ...e, clasificacion FROM animales WHERE animales.hierro = falsa
and my python function is this one
def get_datos_animal(hierro_v):
return "SELECT hierro, registro, nombre, fecha_nacimiento, raza, sexo, hierro_madre, hierro_padre, clasificacion FROM animales WHERE animales.hierro = " + str(hierro_v)
any idea what i´m doing wrong?
Have several functions like this with same errors.
Use the automatic parameter quoting provided by your connection to ensure that values in queries are always quoted correctly, and to avoid SQL injection attacks.
stmt = """SELECT hierro, registro, nombre, fecha_nacimiento, raza, sexo, hierro_madre, hierro_padre, clasificacion
FROM animales
WHERE animales.hierro = %s"""
cursor.execute(stmt, (hierro_v,))
In postgres if you pass value without quotes it will treat that as column name.
Try this:
def get_datos_animal(hierro_v):
return "SELECT hierro, registro, nombre, fecha_nacimiento, raza, sexo, hierro_madre, hierro_padre, clasificacion FROM animales WHERE animales.hierro = '"+str(hierro_v)+"'"

Trouble inserting variable in sqlite python

Im having a problem inserting a variable into sqlite3 and the variable is hashed.
Here's my code:
if passadefinir == passadefinir2:
maindb.execute("DELETE FROM Password WHERE ID = 'not'")
maindb.execute("INSERT INTO Password(ID) VALUES ('set')")
encriptacao = hashlib.sha1(passadefinir2.encode())
encriptado = (encriptacao.hexdigest(),)
maindb.execute("INSERT INTO Password(Password) VALUES (?)" (encriptado,))
conn.commit()
Here's the error:
Traceback (most recent call last):
File "sqlitetesting.py", line 28, in
maindb.execute("INSERT INTO Password(Password) VALUES (?)" (encriptado,))
TypeError: 'str' object is not callable
Have a nice day :D,
Luis Duarte.
You can substitute using String's format method
password_var = 'your password'
insert_statement = 'INSERT INTO Password(Password) VALUES ({0})'.format('\'' + password_var + '\'')
then run the execute method as:
maindb.execute(insert_statement)

python Msql connection with fetchone gives error

I've got a weird problem. I've made a vba code in excel, that calls a python code that get information from the excel sheet and put it into a database. Yesterday there was no problem. Today I start my computer and tried the vba code and it errors in the python file.
The error:
testchipnr = TC104
Traceback (most recent call last):
testchipID = 108
File "S:/3 - Technical/13 - Reports & Templates/13 - Description/DescriptionToDatabase/DescriptionToDatabase.py", line 40, in <module>
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
TypeError: 'NoneType' object has no attribute '__getitem__'
The weird thing is that there is a value in the database -> testchipID ...
My code:
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
print "testchipID = ", cursorOpenShark.fetchone()[0]
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
As you are saying, it was working fine but now it is not, the only reason that I can think of is when your query is returning Zero results.
Looking at your code, if your query is returning only one result, then it will print the result and the next time you are making the call to cursorOpenShark.fetchone() to store in TestchipID it would return None.
Instead, can you try the following code
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
if TestchipID:
print "testchipID = ", TestchipID[0]
else:
print "Returned nothing"
Let me know if this works.

Problem Using Variable in Sqlite3 Statement

I have a problem with a Python 2.7 project.
I'm trying to set a variable to a value retrieved from an sqlite3 database, but I'm having trouble. Here is my code thus far, and the error I'm receiving. Yes, the connection opens just fine, and the table, columns, and indicated row are there as they should be.
import sqlite3 import Trailcrest
conn = sqlite3.connect('roster.paw')
c = conn.cursor()
def Lantern(AI):
"""Pulls all of the data for the selected user."""
Trailcrest.FireAutoHelp = c.execute("""select fireautohelp
from roster
where index = ?;""", (AI,) ).fetchall()
The error is:
> Traceback (most recent call last):
> File "<pyshell#4>", line 1, in <module> Lantern(1)
> File "C:\Users\user\MousePaw Games\Word4Word\PYM\Glyph.py", line 20,
> in Lantern
> Trailcrest.FireAutoHelp = c.execute("""select fireautohelp from roster where index = ?;""", (AI,)).fetchall()
> OperationalError: near "index": syntax error
As Thomas K mentions in a comment, index is a SQL keyword.
You can either rename that column, or enclose in backticks:
Trailcrest.FireAutoHelp = c.execute("""select fireautohelp
from roster
where `index` = ?;""", (AI,) ).fetchall()

Categories

Resources