Python connector error on trying to delete using user input - python

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,))

Related

Check row exists in MySQL through function in python class

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

Python Sqlite3 OperationalError when running UPDATE

I'm running the following Python3 code on a Sqlite3 database:
db.execute("UPDATE user SET ? = ? WHERE id = ?", (name, quantity, str(g.user['id'])))
where db is my cursor object. However, this produces the error
sqlite3.OperationalError: near "?": syntax error.
Is this the right syntax for cursor.execute()?
f-strings would do the job in python3
db.execute(f"UPDATE user SET {name} = {quantity} WHERE id = {str(g.user['id']}"

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)

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.

How to debug the MySQL error message: Caught an exception while rendering

I am building Django +MySQL on dreamhost, but met the error messages:
Caught an exception while rendering: (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 ') ORDER BY tag.used_count DESC, tag.name ASC' at line 1")
I traced hard and found the error splot is with the function below:
Can you someone help me check what's wrong with this code?
def get_tags_by_questions(self, questions):
question_ids = []
for question in questions:
question_ids.append(question.id)
question_ids_str = ','.join([force_unicode(id) for id in question_ids])
related_tags = self.extra(
tables=['tag', 'question_tags'],
where=["tag.id = question_tags.tag_id AND question_tags.question_id IN (" + question_ids_str + ")"]
).distinct()
return related_tags
Is it possible that there are no questions, in which case the SQL will contain something like "WHERE question_id IN ()" which wouldn't be valid SQL.

Categories

Resources