SQL query issue in Django - python

I am trying to find out if a value is present in a column in a MySQL table from my django application. This is what I have done:
cursor = connection.cursor()
cursor.execute('SELECT COUNT(*) FROM model_combination_bank WHERE combination = %s AND validity = 1', [combination])
result = cursor.fetchall
if result != 1:
self.respond('Sorry. The entry code you entered is not valid. Please try again with a valid code.')
return()
I know for sure that there is a 1 row in the table that matches the SELECT STATEMENT but the self.respond function runs. Can somebody kindly tell me whats wrong with my code.

You didn't call the method:
result = cursor.fetchall()
However you shouldn't really be using raw SQL here. Use the model layer:
result = ModelCombinationBank.objects.filter(validity=1, combination=combination).count()
assuming your model is called ModelCombinationBank. And if all you need to is to check that the combination exists, use exists() instead of count(), since that is a cheaper query.

Another way to see if a value exists and do something if it does:
try:
obj = ModelCombinationBank.objects.get(validity=1, combination=combination)
# do something with obj
except ModelCombinationBank.DoesNotExist:
# do something if not found

Related

What does return SELECT when couldn't find the value it's searching for (in SQL)?

I'm doing an exercise where I need to update some values in a table of SQL DB via python and I can't find out what SELECT return if "user" AND another "X-condition" are NOT found in the database.
I read in another thread SELECT should return an empty set, but I still got a problem with it!
When I run:
example = db.execute("SELECT value FROM table1 WHERE user=:user AND X=:Y", user=user, X=Y)
and I try with a condition like
if example == {}:
db.execute("INSERT [...]")
I never go inside this condition to do the INSERT stuff when the set is empty.
I found another route to solve this (write below), but is it valid at all?
if not example:
do the job
EDIT: I'm using sqlite3!
Assuming you're using sqlite3, the execute method always returns a Cursor which you can use to fetch the result rows, if there were any. It doesn't matter what kind of query you were doing.
If the first result you fetch is None right away, there weren't any rows returned:
if example.fetchone() is None:
db.execute("INSERT [...]")
Alternatively, you could fetch all rows as a list, and compare that against the empty list:
if example.fetchall() == []:
db.execute("INSERT [...]")

How to check for empty results in a cursor? (flask + pymysql)

I dont know how to check for empty results from a cursor.execute.
Say I have a empty table Brand. I do:
cursor.execute("SELECT * FROM Brand")
db.commit()
results = cursor.fetchall()
return render_template("index.html", results = results)
and this pops up on the website:
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
Wanted a fix, maybe a if statement to check if the results are empty..
You can use
if cursor.rowcount == 0 # empty results
And you don't need db.commit() as mentioned in the comments.

Python mysql output from function not working

I'm relatively new at Python but have more experience in Java, so I understand most of the concepts. However, I keep having issues with MySQL and passing information back from a function using MySQL
to use in another function later.
I need to make complex MySQL queries with multiple return field, So I don't want to be running multiple SQL queries for each SQL field as this will smash the database.
Saying that the below is a small example of what I'm trying to achieve.
I wanted a function to run an SQL query (def connectory_mysql()) that took parameters from elsewhere, (this part works) then take the output of the SQL query and pass back to the main function to use.
The main function then needs to use the different column results of the SQL query for different parameters.
I can return the result and assign it to a result1 which appears and looks like a dictionary when printed, but I'm unable to split/use the different keys or data from the result1 = connector_mysql(subSerialNum, ldev, today_date)
If i splituse the keys in the dictionary in the SQL function before returning ie ldev_cap = result['ldev_cap']
I can print the individual elements within the SQL function... However, I cant seem to pass the parameters then back to the main function and split them out??
I must have missed something easy or am not understanding something... any assistance or help would be greatly appreciated...
...
result1 = connector_mysql(subSerialNum, ldev, today_date)
print(result1) #this works and appears to be a dictionary, but I can split it
## into its elements like:
ldev_cap = result1['ldev_cap'] ##-> this dosn't work here.....???? if i return it as a dictonary..
#and i'm unsure how to split them when i pass just the paramaters
#back if i split the dictionary in the sql function.
...
def connector_mysql(subSerialNum, ldev, today_date):
import pymysql.cursors
db_server = 'localhost'
db_name = 'CBDB'
db_pass = 'secure_password'
db_user = 'user1'
sql_query = (
"SELECT ldev_cap, ldev_usdcap FROM Ldevs WHERE sub_serial=%(serial)s "
"and ldev_id=%(lun)s and data_date=%(todayD)s")
connection = pymysql.connect(host=db_server,
user=db_user,
password=db_pass,
db=db_name,
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
cursor.execute(sql_query, {'serial': subSerialNum, 'lun': ldev, 'todayD': today_date})
result = cursor.fetchone()
while result:
ldev_cap = result['ldev_cap'] #here the dictionary acts as
#expected and i can assign a value
ldev_usdcap = result['ldev_usdcap']
print(result)
return ldev_cap, ldev_usdcap #here i can return
finally:
connection.close()
Any help or assistance would be greatly apricated...
Cheers
Graham
First of all, you should get familiar with the Python style guide for writing python code.
Based on your existing code, result1 return as a tuple that contained the value of (ldev_cap, ldef_usdcap) (it is not a directory). You get access to the return result as result1[0] which corresponding to the return value of ldev_cap or result1[1] which corresponding to the return value of ldev_usdcap.
Alternatively, since you are returning two data, you can access each return data by using
ldev_cap, ldev_usdcap = connector_mysql(subSerialNum, ldev, today_date)

How to check if a table exists using python?

I want to check whether the table exists or not before inserting the data.
This is what i have tried:
def checkTables(tablename):
stmt = "SHOW TABLES LIKE %s"%tablename
cursor.execute(stmt)
result = cursor.fetchone()
return result
But it gives me error saying:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ctg_payload3' at line 1
Maybe it is not the best way.
As for my opinion, I will show tables;, then search the result.
And, I you cannot execute show tables like tablename;, no syntax like that.
edit 1
If you must do it in sql, use
show table status like 'table_name';
' is needed for this sql.
Try this query string :SHOW TABLES WHERE Tables_in_mydb LIKE '%tablename%' or
this one
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'my_database_name'
AND table_name LIKE '%tablename%'
Good luck
Try this.
def checkTables(tablename):
stmt = "SHOW TABLES LIKE '%s' "% ('%'+str(tablename)+'%')
cursor.execute(stmt)
result = cursor.fetchone()
return result

Return last inserted ID sqlalchemy sqlite

I'm trying to get the last inserted row id from an sqlalchemy insert with sqlite. It appears this should be easy but I haven't managed to figure it out yet and didn't find anything in my searches so far. I'm a new to python and I know there are some similar posts so I hope this is not a repeat. Below is some simple sample script:
from sqlalchemy import *
engine = create_engine('sqlite:///myTest.db',echo=False)
metadata = MetaData()
dbTable1 = Table('dbTable1', metadata,Column('ThisNum', Integer),Column('ThisString', String))
metadata.create_all(engine)
dbConn = engine.connect()
insertList={}
insertList['ThisNum']=1
insertList['ThisString']='test'
insertStatement = dbTable1.insert().values(insertList)
lastInsertID = dbConn.execute(insertStatement).inserted_primary_key
The value returned is empty. I get the same result using
lastInsertID = dbConn.execute(insertStatement).last_inserted_ids()
I can get the last rowid using a separate statement after the insert:
lastInsertID = dbConn.execute('SELECT last_insert_rowid();')
But this would not guarantee the database had not been accessed in between the executions so the returned ID might not be correct. Lastly I tried executing the insert and select statements in one execution for instance:
lastInsertID = dbConn.execute('INSERT INTO "dbTable1" ("ThisNum", "ThisString") VALUES (1, "test"); SELECT last_insert_rowid();')
But this gives the error: sqlite3.Warning: You can only execute one statement at a time.
Any help would be appreciated. Thanks.

Categories