MySQL - Query has to many arguments when select with variable - mysql

I am switching from SQLite to MySQL and getting some problems with my Queries. At the moment i am trying to SELECT from a Table where the PackageName is like a variable from a Text Input in my GUI.
The Query looks like this:
test = self.ms.ExecQuery("SELECT PackageID,PackageName,ServiceFee,Cost,LatestChanges FROM Package WHERE PackageName=?", (self.search_entry.GetValue(),))
and my ExecQuery looks like this:
def ExecQuery(self, sql):
cur = self._Getconnect()
cur.execute(sql)
relist = cur.fetchall()
cur.close()
self.conn.close()
return relist
And the error i am getting:
TypeError: ExecQuery() takes 2 positional arguments but 3 were given
What do i need to change to get this running?

You have sql as the 2nd parameter in your ExecQuery, yet you are passing in a sql query as the 1st parameter:
test = self.ms.ExecQuery("SELECT PackageID,PackageName,ServiceFee,Cost,LatestChanges FROM Package WHERE PackageName=?", (self.search_entry.GetValue(),))

Related

Why is unwanted characters being printed on the sql query result?

I am querying my SQL table using the code below and converted the result to a list. Why is the list having unwanted commas and parenthesis?
The query result
[(34830,), (34650,), (35050,), (34500,), (35050,), (34500,), (34725,), (34550,), (34725,), (34760,), (34760,)]
It should just return a list with just numbers on it. Right?
The schema is simple (link text, price int);
What is the problem here? Is there something wrong with my code?
import pymysql
connection = pymysql.connect(host='localhost',
user='root',
password='passme',
db='hpsize') # connection obhect to pass the database details
sql = "SELECT price FROM dummy WHERE link ='https://www.flipkart.com/bose-noise-cancelling-700-anc-enabled-bluetooth-headset/p/itma57a01d3bd591?pid=ACCFGYZEVVGYM8FP'"
my_cursor = connection.cursor()
my_cursor.execute(sql)
result = list(my_cursor.fetchall())
print(result)
connection.close()
The query result
[(34830,), (34650,), (35050,), (34500,), (35050,), (34500,), (34725,), (34550,), (34725,), (34760,), (34760,)]
try
connection.row_factory = lambda cursor, row: row[0]
instead of list(my_cursor.fetchall())
then
result = connection.execute("""SELECT * FROM dummy""").fetchall()
or you can also use strip() to cut the unwanted part

mysql query using python 3.6 (string variable is in single quotes)

I am new in python as well as mysql. I am having trouble in populating proper query statement for mysql.
sql = "SELECT * FROM Persons WHERE %s"
cur = db.cursor()
cur.execute(sql,(where,))
where is a string variable which creates a string for WHERE clause; this is the point of question. When I print this variable it give the following result:
Gender = True And IsLate = False
(without any quotes) but when I add this variable to the query to execute it, it adds single quotes around the string.
I used the command
print(cur.statement)
and it prints:
SELECT * FROM Persons WHERE 'Gender = True And IsLate = False'
After supplying parameter, it puts it within single quotes and query returns 0 rows.
I have worked around by concatenating the query statement and variable together and execute the string as query, that worked,
sql = sql + where
cur.execute(sql)
But I know that is not the professional way, as I have searched and found the professional way is to use parameterized query and use variable to store the condition(s) and supplying it at the execution of query.
Looking for advice, am I thinking the right way or otherwise?
The whole point of using parameter substitution in cursor.execute() is that it protects you from SQL injection. Each parameter is treated as a literal value, not substituted into the query and re-interpreted.
If you really want it to be interprted, you need to use string formatting or concatenation, as you discovered. But then you will have to be very careful in validating the input, because the user can supply extra SQL code that you may not have expected, and cause the query to malfunction.
What you should do is build the where string and parameter list dynamically.
where = []
params = []
if gender_supplied:
where.append('gender = %s')
params.append(gender)
if islate_supplied:
where.append*('islate = %s')
params.append(islate)
sql = 'select * from persons'
if where:
query = sql + ' where ' + ' and '.join(where)
else:
query = sql
cur.execute(query, params)

Unable to retrieve data from my sql database using pymysql

I have been trying to retrieve data from my database. I was successful, however, this time inside an if statement. The code looks like:
cur_msql = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
select_query = """select x,y,z from table where type='sample' and code=%s"""
cur_msql.execute(select_query, code)
result2 = cur_msql.fetchone()
if(result2==None):
insert_func(code)
select_query = f"""select x,y,z from table where type='sample' and code='{code}'"""
mycur = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
print(select_query)
mycur.execute(select_query)
result3 = mycur.fetchone()
if(result2==None):
result2=result3
Now I see that insert_func does successfully insert into the 'table'. However, on trying to fetch that row, immediately after the insertion, it returns None as if the row is absent. On debugging I find that result3 is also None. Nothing looks wrong to me but it's not working.
you donĀ“t execute it in the right way, in the cur_msql.execute, you the to send the query and a tuple of values, and you are sending just a value:
cur_msql = conn_mysql.cursor(cursor=pymysql.cursors.DictCursor)
select_query = "select learnpath_code,learnpath_id,learnpath_name from contentgrail.knowledge_vectors_test where Type='chapters' and code=%s"
cur_msql.execute(select_query, (meta['chapter_code'],))
result2 = cur_msql.fetchone()

Quering with Python Connector with variables

i am new in python and i have a simple issue that i cannot resolve.
I am in windows platform and unfortunately i cannot change this cause of work. I have to connect to many mysql tables and do sort of things with the extracted data. The code that i have:
conn = mysql.connector.Connect(host='<ip>',user='<user>',\
password='',database='<my database>')
c = conn.cursor()
c.execute ("select field from TABLE")
results = c.fetchall()
for row in results:
c.execute("select * from otherTable where nodo = %s",(str(row[0])))
if c.rowcount == 0:
doSomething()
else:
doOtherThing()
c.close()
when I run this with Python34 i got the error:
"you have an error in your sql synthax; check the manual that corresponds to your mysql server version for the right synthax to use near '%s' at line 1
thanks
you need to put single quotes around your %s like this: c.execute("select * from otherTable where nodo = '%s'",(str(row[0])))
you should also consider putting your query in a variable and then executing it like so:
query = ("select * from otherTable where nodo = '%s'",(str(row[0])))
c.execute(query)
This way helps prevents potential sql injection attacks and allows you to do a print(query) so you can debug the sql statement if you are getting errors.

Django Call Stored Procedure on Second Database

I'm trying to call a stored procedure on a multi-db Django installation, but am not having any luck getting results. The stored procedure (which is on the secondary database) always returns an empty array in Django, but the expected result does appear when executed in a mysql client.
My view.py file
from SomeDBModel import models
from django.db import connection
def index(request, someid):
#Some related django-style query that works here
loc = getLocationPath(someid, 1)
print(loc)
def getLocationPath(id, someval):
cursor = connection.cursor()
cursor.callproc("SomeDB.spGetLocationPath", [id, someval])
results = cursor.fetchall()
cursor.close()
return results
I have also tried:
from SomeDBModel import models
from django.db import connections
def index(request, someid):
#Some related Django-style query that works here
loc = getLocationPath(someid, 1)
print(loc)
def getLocationPath(id, someval):
cursor = connections["SomeDB"].cursor()
cursor.callproc("spGetLocationPath", [id, someval])
results = cursor.fetchall()
cursor.close()
return results
Each time I print out the results, I get:
[]
Example of data that should be retrieved:
{
Path: '/some/path/',
LocalPath: 'S:\Some\local\Path',
Folder: 'SomeFolderName',
Code: 'SomeCode'
}
One thing I also tried was to print the result of cursor.callproc. I get:
(id, someval)
Also, printing the result of cursor._executed gives:
b'SELECT #_SomeDB.spGetLocationPath_arg1, #_SomeDB.spGetLocationPath_arg2'
Which seems to not have any reference to the stored procedure I want to run at all. I have even tried this as a last resort:
cursor.execute("CALL spGetLocationPath("+str(id)+","+str(someval)+")")
but I get an error about needing multi=True, but putting it in the execute() function doesn't seem to work like some sites have suggested, and I don't know where else to put it in Django.
So...any ideas what I missed? How can I get stored procedures to work?
These are the following steps that I took:
Made my stored procedure dump results into a temporary table so as to flatten the result set to a single result set. This got rid of the need for multi=True
In addition, I made sure the user at my IP address had access to call stored procedures in the database itself.
Finally, I continued to research the callproc function. Eventually someone on another site suggested the following code, which worked:
cur = connections["SomeDB"].cursor()
cur.callproc("spGetLocationPath", [id, someval])
res = next(cur.stored_results()).fetchall()
cur.close()