Mysql AES_DECRYPT() function not working in Django raw query - python

When I use MySql function AES_DECRYPT() in a raw query in Django, this function didn't work. My code is like this:
sql = "select AES_DECRYPT(myfield, mykey) as ssn from mytable "
people_list = Peopletable.objects.raw(sql)
for p in people_list:
print p.ssn
It printed out None, which means AES_DECRYPT() didn't work. But if I run the query in python side then I get what I need. I tried other mysql functions like SUBSTR() and they worked perfectly. Seems like only this AES_DECRYPT() doesn't work in Django. Can anyone help? Thanks a lot!

It doesn't actually mean it doesn't work just that result of AES_DECRYPT(myfield, mykey) is None (null).
If AES_DECRYPT() detects invalid data or incorrect padding, it returns NULL. However, it is possible for AES_DECRYPT() to return a non-NULL value (possibly garbage) if the input data or the key is invalid.
Try to run same query directly on database it will probably have same result.

Related

Python Unable to Find SQL Value From Database

I have been working with an SQL database through the mySQL library in Python. I have recently found that when I try searching for a string in my database, it is not correctly returning the output I expect. I think this may be due to my variable not being properly inserted into my SQL command.
code = data['code']
sql = "SELECT 200 FROM mytable WHERE mycolumn = '%s';"
query.execute(sql, teamCode)
print(str(query.fetchall()))
My problem is that printing query.fetchall() prints an empty list ([]) instead of the expected [[200,]] which means the program thinks the code value it is using does not exist in the SQL database, which it does.
The parameters in an execute call need to be a sequence, like a tuple. Try:
query.excute(sql, (teamCode,))
That turns it into a one-element tuple. BTW, did you really mean "code" there?

Getting error when running a sql select statement in python

I am new to this and trying to learn python. I wrote a select statement in python where I used a parameter
Select """cln.customer_uid = """[(num_cuid_number)])
TypeError: string indices must be integers
Agree with the others, this doesn't look really like Python by itself.
I will see even without seeing the rest of that code I'll guess the [(num_cuid_number)] value(s) being returned is a string, so you'll want to convert it to integer for the select statement to process.
num_cuid_number is most likely a string in your code; the string indices are the ones in the square brackets. So please first check your data variable to see what you received there. Also, I think that num_cuid_number is a string, while it should be in an integer value.
Let me give you an example for the python code to execute: (Just for the reference: I have used SQLAlchemy with flask)
#app.route('/get_data/')
def get_data():
base_sql="""
SELECT cln.customer_uid='%s' from cln
""" % (num_cuid_number)
data = db.session.execute(base_sql).fetchall()
Pretty sure you are trying to create a select statement with a "where" clause here. There are many ways to do this, for example using raw sql, the query should look similar to this:
query = "SELECT * FROM cln WHERE customer_uid = %s"
parameters = (num_cuid_number,)
separating the parameters from the query is secure. You can then take these 2 variables and execute them with your db engine like
results = db.execute(query, parameters)
This will work, however, especially in Python, it is more common to use a package like SQLAlchemy to make queries more "flexible" (in other words, without manually constructing an actual string as a query string). You can do the same thing using SQLAlchemy core functionality
query = cln.select()
query = query.where(cln.customer_uid == num_cuid_number)
results = db.execute(query)
Note: I simplified "db" in both examples, you'd actually use a cursor, session, engine or similar to execute your queries, but that wasn't your question.

Python Replace Quoted Values In External SQL Query

I use the simple query below to select from a table based on the date:
select * from tbl where date = '2019-10-01'
The simple query is part of a much larger query that extracts information from many tables on the same server. I don't have execute access on the server, so I can't install a stored procedure to make my life easier. Instead, I read the query into Python and try to replace certain values inside single quote strings, such as:
select * from tbl where date = '<InForceDate>'
I use a simple Python function (below) to replace with another value like 2019-10-01, but the str.replace() function isn't replacing when I look at the output. However, I tried this with a value like that wasn't in quotes and it worked. I'm sure I'm missing something fundamental, but haven't uncovered why it works without quotes and fails with quotes.
Python:
def generate_sql(sql_path, inforce_date):
with open(pd_sql_path, 'r') as sql_file:
sql_string = sql_file.read()
sql_final = str.replace(sql_string, r'<InForceDate>', inforce_date)
return(sql_final)
Can anyone point me in the right direction?
Nevermind folks -- problem solved, but haven't quite figured out why. File encoding is my guess.

python variable invalid syntax issue

I'm having an issue getting what I think is a simple script working and I think it's just me not knowing how to get a variable working.
i'm working on a salesforce script that grabs a list of objects, then looks through the list of objects to get all fields on the table.
this query in python works perfectly for giving me my list of objects that I've pulled into the DB
query = ("SELECT obj_name FROM syncsfobjects")
cursor.execute(query)
i then loop through these records
for x in cursor:
now this is where my issue lies I want to use the obj_name that comes in from my query within the next statement
for xy in sf.%obj_name%.describe()["field"]:
what i'm having massive issues with is getting the obj name into this simple-salesforce query.
if I create a string it works fine
objectname = str(x)
sfquery = 'sf. %s .describe()["fields"]' % objectname
but then when I use the sfquery for my next loop all the loop does it run through each letter within the string instead of run the sf connection command.
any I just missing something simple?
cheers
dan
for xy in sf.%obj_name%.describe()["field"]:
Python doesn't let you do "percent substitution" outside of strings, but you can still access attributes if all you have are their names:
for xy in getattr(sf, objectname).describe()["field"]:

None is returned when using cursor.fetchone() to select count()

I wrote a sql like this:
"select count(md5) from table_file_log where md5=\'%s\'" % my_md5
my_md5 is a string passed to the method.
When I used fetchone() I got None returned.
Actually I usually prefer fetchall() to avoid None returned, but I believe count() should get (0,) instead of None, even if there is no record.
I added logging to print the sql and pasted it in mysql and correct count was returned.
One more thing, in my program, hundreds of the same kind of sql got executed, and some of them got None, some of them got correct results like (0,) or (1,).
I tried to search solutions on this site, the only post I found that seemed related to my question is this:
cursor.fetchone() returns None but row in the database exists
But I don't understand why autocommit would work in that question. Even if that's the answer I would like to know the reason.
I use Python 2.7 and mysql-connector, and MyISAM as the engine.

Categories