Trouble inserting variable in sqlite python - 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)

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

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

Impossible to insert data with PyMySQL when I use parameter

I'm currently working on a basic query which insert data depending on the input parameters, and I'm unable to perfom it.
cur.execute("INSERT INTO foo (bar1, bar2) values (?, ?)", (foo1, foo2))
I have this error message:
Exception in Tkinter callback Traceback (most recent call last):
File "/usr/lib/python3.2/tkinter/init.py", line 1426, in call
return self.func(*args) File "test.py", line 9, in register
cur.execute("INSERT INTO foo (bar1, bar2) values (?,?)", (foo1, foo2)) File
"/usr/local/lib/python3.2/dist-packages/pymysql/cursors.py", line 108,
in execute
query = query % escaped_args TypeError: unsupported operand type(s) for %: 'bytes' and 'tuple'
foo1 and foo2 are both string type. I tried with %s, same error.
It seems like a bug in cursors.py. As suggested here and here you should replace this line in cursors.py:
query = query % conn.escape(args)
With this:
query = query.decode(charset) % conn.escape(args)
In case it didn't work try this one instead:
query = query.decode(charset) % escaped_args

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