HARSHIT BAJPAI
HARSHIT BAJPAI

Reputation: 670

Check if an email already exists in MysqlDB Python

I am trying to check if email exsists in my MYSQL table. I am able to successfully connect to the DB and execute SQL queries on the table. But on checking for an email, it gives a SyntaxError on '@' as invalid syntax. I have tried using escape character('\') but it still gives me the same error.

import MySQLdb

# Connect
mydb = MySQLdb.connect(host="localhost",
                    port=3000,
                     user="root",
                     passwd="xxxxxx",
                     db="xxxxxx")

sqlquery = " select * from <tablename> where email = %s"

mycursor.execute(sqlquery, [email protected])

#on using quotes around string
#mycursor.execute(sqlquery, '[email protected]')
#TypeError: not all arguments converted during string formatting

#row_count = mycursor.rowcount
#print(row_count)

Output

(kp_env) storm@storm:/mnt/d$ python abc.py
  File "abc.py", line 40
    mycursor.execute(sqlquery, [email protected])
                                  ^
SyntaxError: invalid syntax

Also if there is a better way to check if the email exists in the table or not, let me know.

Upvotes: 1

Views: 430

Answers (1)

nbk
nbk

Reputation: 49385

Your string need doubleqoutoes to be identifies as one string and you need to use a tuple even fpor one parameters

import MySQLdb

# Connect
mydb = MySQLdb.connect(host="localhost",
                    port=3000,
                     user="root",
                     passwd="xxxxxx",
                     db="xxxxxx")

sqlquery = "select * from <tablename> where email = %s"

mycursor.execute(sqlquery, ("[email protected]",))

I personally prefer import mysql.connector

It is newer and makes less problems.

Upvotes: 1

Related Questions