Executing python function in postgres - python

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)+"'"

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})')

Python - MySQLdb parametrized query

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

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)

pymysql: MySQL Parameterized LIKE Query

Why am I getting TypeError: not all arguments converted during string formatting when trying to execute this query? I need to be able to append %{}% to the IP I am passing in so that i can run a LIKE mysql query.
If this isn't the correct way to parameterize a LIKE query using the % wildcard, how do you do this?
Class:
class IpCleaner(object):
def __init__(self, ip):
self.ip = ip
self.iplike = '%{}%'.format(self.ip)
def lookup(self):
self.dbconnect()
select_query = (
"SELECT `name`,`source`,`destination` FROM mytable "
"WHERE (`source` LIKE ? OR `destination` ? );"
)
params = [self.iplike, self.iplike]
print params
self.cur.execute(select_query, params)
print self.cur.fetchall()
Instantiation:
a = IpCleaner('74.121.242.2')
a.lookup()
output:
Traceback (most recent call last):
['%74.121.242.2%', '%74.121.242.2%']
File "/home/dobbs/shunlibs/IpCleaner.py", line 87, in <module>
a.palorulelookup()
File "/home/dobbs/shunlibs/IpCleaner.py", line 81, in lookup
self.cur.execute(select_query, params)
File "/usr/lib64/python2.7/site-packages/pymysql/cursors.py", line 164, in execute
query = self.mogrify(query, args)
File "/usr/lib64/python2.7/site-packages/pymysql/cursors.py", line 143, in mogrify
query = query % self._escape_args(args, conn)
TypeError: not all arguments converted during string formatting
use %s instead of ? in the select_query variable

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