Check row exists in MySQL through function in python class - python

I am trying to implement a function in my database manager class that checks if a row (user) exists (through their email) in my MySQL table.
See code below:
def has_user(self, table_name : str, user_credentials: UserCredentials) -> bool:
mysql_hasuser_query = """
SELECT COUNT(1) FROM {t_name} WHERE email = {u_email}
""".format(t_name=table_name, u_email=user_credentials.email)
cursor = self.connection.cursor()
cursor.execute(mysql_hasuser_query)
if cursor.fetchone()[0]:
print("User exists in database!")
return True
I am receiving the following syntax error mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '#gmail.com' at line 1
However, I implemented this in MySQL query editor and it worked fine. I am not sure what I am doing wrong here.

You're not quoting the email in the query. But you should use a parameter instead of formatting the string into the query.
def has_user(self, table_name : str, user_credentials: UserCredentials) -> bool:
mysql_hasuser_query = """
SELECT COUNT(1) FROM {t_name} WHERE email = %s
""".format(t_name=table_name)
cursor = self.connection.cursor()
cursor.execute(mysql_hasuser_query, (user_credentials.email,))
if cursor.fetchone()[0]:
print("User exists in database!")
return True

Related

Facing issues in Python to MYSQL insertion

I've tried to use couple of methods to insert data into mysql database but getting error in all:
In the first method:
sql = ('''Insert into lgemployees (EmpID,Name,Gender,DOB,Address,PhoneNumber,Email)
VALUES (%d,$s,$s,$s,$s,$d,$s)''', (eid, name, gen, dob, add, mob, email))
mycursor.execute(sql)
mycursor.commit()
Error in this approach:
'tuple' object has no attribute 'encode'
2nd method:
sql = "Insert into lgemployees (EmpID,Name,Gender,DOB,Address,PhoneNumber,Email) VALUES(?,?,?,?,?,?,?,)"
val = (eid, name, gen, dob, add, mob, email)
mycursor.execute(sql, val)
mycursor.commit()
Error in this approach :
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
I've troubleshooted a lot from my end but no luck. Can any one please help as where am I wrong or what else can be a good option to insert data into mysql from python.
I dont know where you error is at, but ive tested with this code and it works.
insert_tuple = (eid, name, gen, dob, add, mob, email)
sql = """INSERT INTO lgemployees (`EmpID `,
`Name`,`Gender`, `DOB`, `Address`, `PhoneNumber`, `Email`)
VALUES (%s,%s,%s,%s,%s,%s,%s)"""
mycursor = mySQLconnection.cursor()
mycursor.execute(sql, insert_tuple)
mySQLconnection.commit()
mycursor.close()
your code throws this because one of the parameters are empty or are in a format it cant read.
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

MySQL/Python connector not being able to search [duplicate]

This question already has an answer here:
MySQL/Python -> Wrong Syntax for Placeholder in Statements?
(1 answer)
Closed 4 years ago.
import mysql.connector
config = {
'user': 'root',
'password': '*******',
'host': '127.0.0.1',
'database': 'mydb',
'raise_on_warnings': True
}
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
find_user = ("SELECT * FROM HM_Login WHERE Username = '%s' ")
data_Pupil = {
'Username': "GJM"
}
cursor.execute(find_user, data_Pupil)
lit = cursor.fetchall()
print(lit)
cursor.close()
cnx.close()
I have a database that works and i am having a problem trying to search the database and pull one row of one column when i was inserting into the database the %S worked just fine but now it only works if i have a value inside the the query. this is using the mysql connector for python.
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '' at line 1
I am getting this error which is extremely insightful and not helpful at all if there is anything you can do to help it would mean a lot.
As the error statement says. You have an SQL error. You are trying to input a variable as a positional parameter but you've used a dictionary on a variables 'place'.
Instead you should use %s for variables and tuples with variables and then do the following:
find_user = "SELECT * FROM HM_Login WHERE Username = %s"
data_Pupil = ('GJM',)
cursor.execute(find_user, data_Pupil)
It is also possible to use dictionary - but you shouldn't. Despite that I'm still going to show it here as I had to dig into the explanation to understand why.
find_user = "SELECT * FROM HM_Login WHERE Username = '{Username}'".format(**data_Pupil)
data_Pupil = {
'Username': "GJM"
}
The above opens up for sql-injections, as I was told per the comments - and here is why; Say we have a username that is identical to the following:
username = "'MR SQL Injection');DROP TABLE HM_Login;"
That would result in an SQL Query that drops the table.
SELECT * FROM HM_Login WHERE Username = 'MR SQL Injection');DROP TABLE HM_Login;
To avoid sql-injection as above. Use the first solution
Your placeholder syntax is for positional parameters but you've used a dictionary. Replace that with a tuple:
find_user = ("SELECT * FROM HM_Login WHERE Username = %s")
data_pupil = ('GJM',)
cursor.execute(find_user, data_Pupil)

Python connector error on trying to delete using user input

I have implemented most other basic database transactions including insert,update,select with similar syntax,but on trying to delete,i get error
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%s' at line 1
What would the correct syntax be? I must delete according to user input. Here is a shortened version of my code,minus the insert,select,update part.:
elif (choice == 4):
mail=raw_input('Enter email of user to be deleted:')
print 'Deleting..'
delete_user_details(mail)
def delete_user_details(email):
sql = "DELETE FROM users WHERE email = %s"
cursor.execute(sql,email)
You need to pass query parameters to cursor.execute() as a tuple, even for a single parameter. Try this:
sql = "DELETE FROM users WHERE email = %s"
cursor.execute(sql, (email,))

Python aiomysql puts a set of quote around my query argument

I'm using python's aiomysql execute function to execute sql queries.
#asyncio.coroutine
def select(sql,args=None,size=None):
log(sql,args)
global __pool
with (yield from __pool) as conn:
cur = yield from conn.cursor()
yield from cur.execute(sql.replace('?','%s'),args or ())
if size:
rs = yield from cur.fetchmany(size)
else:
rs = yield from cur.fetchall()
__pool.close()
yield from __pool.wait_closed()
return rs
In the test function I did
#asyncio.coroutine
def test():
yield from create_pool(loop=loop,user='app',passwd='app')
sql = 'select ? from ?'
arg = ['id','users']
rs = yield from select(sql,arg)
print(rs)
global __pool
__pool.close()
yield from __pool.wait_closed()
In the terminal I got an error
pymysql.err.ProgrammingError: (1064, "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 ''users'' at line 1")
There appears to be a set of quote around users. I tried changing the last ? to %s and that somehow worked, apparently the ? worked for id but not for users. Why is there a set of quote around users and how can I fix it?
Thank your for your answer
SQL parameters cannot be used for metadata with MySQL. You will need to sanitize the value and substitute it normally.
For anyone else that might have the same problem, it seems like it's impossible to use arg to refer to the tables, the table must be specified before passing into execute

Why would a "user is taken" method that queries a MySQL database pass an immutable dict?

I am creating a Flask Application that connects to a locally-hosted MySQL database (Using SQL-Alchemy ORM). When a user creates an account, I have a method is_taken and returns True or False depending on if a user with that username already exists.
Here is the method:
def is_taken(username):
q = session.query(User).filter(User.username == username).first()
return not (q is None)
Although not on a regular basis, the following error occurs at least once a day:
StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect
until invalid transaction is rolled back [SQL: u'SELECT users.uid AS
users_uid, users.username AS users_username, users.fullname AS
users_fullname, users.password AS users_password, users.score AS
users_score, users.totalattempted AS users_totalattempted,
users.totalcorrect AS users_totalcorrect, users.settings AS
users_settings \nFROM users \nWHERE users.username = %s \n LIMIT
%s'] [parameters: [immutabledict({})]]
The error is triggered specifically on:
q = session.query(User).filter(User.username == username).first()
I appreciate the help!
you've had a invalid transaction before executing this query. first of all I suggest you to find the problem of previous query that led to this problem. and for fixing this problem you execute session.rollback() before running the query.

Categories

Resources