Check if an email already exists in MysqlDB Python - 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, abc#def.com)
#on using quotes around string
#mycursor.execute(sqlquery, 'abc#def.com')
#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, abc#def.com)
^
SyntaxError: invalid syntax
Also if there is a better way to check if the email exists in the table or not, let me know.

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, ("abc#def.com",))
I personally prefer import mysql.connector
It is newer and makes less problems.

Related

How to store a hashed password to database?

I'm using Python 3 and mysql.connector module. I could not store the hased password to the database.
Here is my code:
import bcrypt
import base64, hashlib
import mysql.connector
class test:
def __init__(self):
self.cnx = mysql.connector.connect(**Connect)
self.cursor = self.cnx.cursor()
pw = "Test123!"
password=pw.encode('utf-8')
hash_pass = bcrypt.hashpw(base64.b64encode(hashlib.sha256(password).digest()),bcrypt.gensalt())
print(hash_pass)
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
self.cnx.commit()
test()
When I run the INSERT statement, the error occurred:
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 '$2b$12$2Jo8.yam0VU5IKQxMa4EV.ReuFGeG43wmzbrFDsT5Pr5c8L2rmlP6'')' at line 1
Noted: My datatype for password is CHAR(96)
I appreciate your help.
Use query parameters instead of string-formatting.
// WRONG
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
// RIGHT
self.cursor.execute("INSERT INTO test (password) VALUE (%s)", (hash_pass,))
Both methods use %s as a placeholder, which is kind of confusing because it looks like it's doing the same thing. But the latter is not doing simple string substitution. It makes the value safe for the SQL query, either by escaping special characters, or by doing true query parameters, keeping the value separate until after the query has been parsed.

Question about creating table using psycopg2's sql module

'''
host = "localhost"
user = "postgres"
password = "Lall1739!##"
port = "5432"
dbname = "snp500"
con_form = "host={0} user={1} password={2} port={3} dbname={4}".format(host, user, password, port, dbname)
con = psycopg2.connect(con_form)
cur = con.cursor()
components_name, components_prices, components_fetch_dates = fetch_investing_snp500_components_datas()
for component_name in components_name:
table_name = component_name
cur.execute(
query=sql.SQL("CREATE TABLE %s"),
vars=(sql.Identifier(table_name))
)
'''
TypeError: 'Identifier' object does not support indexing
It's also not a good idea to use Python string interpolation to build the query string.
So I am trying to write a query using the sql module.
What exactly are the benefits of writing a query using the sql module and why am I getting a Type error?
Note that execute is used for parameter substitution (.i.e. string literals), whereas you want to substitute identifiers (i.e. table names). Use SQL.format() for that:
cur.execute(
query=sql.SQL("CREATE TABLE {table}").format(
table=sql.Identifier(table_name),
),
)

How to fix "InterfaceError: No result set to fetch" from in python using mysql

I'm trying to run a select query in my already populated database through the mysql connector in python, and print the results.
I've checked the query "SELECT * FROM employee" in the mysql console and it works. I could not find an error in my code. Note that I can successfully insert rows into the database(so the credentials are correct). I looked around for a solution, but none of them were my exact problem. Here is my code:
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "....",
database = "officeplanning")
mycursor = mydb.cursor()
query = "SELECT * FROM employee"
mycursor.execute(query)
myresult = mycursor.fetchall()
for row in myresult: print(row)
I should be getting a list printed in the console, but instead I am getting the error:
File "C:\Users\Anubhab\Anaconda3\lib\site-packages\mysql\connector\cursor_cext.py", line 489, in fetchall
raise errors.InterfaceError("No result set to fetch from.")
InterfaceError: No result set to fetch from.
Edit: I did not call the fetchall() function twice (which caused the issue in that case) unlike the duplicate suggestion.

How to import sql via shell in Python?

I have case :
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/opt/lampp/var/mysql/mysql.sock', user='root', passwd=None, db='test')
cur = conn.cursor()
cur.execute("test < /mypath/test.sql")
cur.close()
conn.close()
I always get error :
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 'test < /mypath/test.sql' at line 1"
I tried to use source and it still failed. Did you know why?
Thank you.
Your error message says that the MySQL server can't understand
test < /mypath/test.sql' at line 1
If you're a long time *nix user, it seems intuitive that you should be able to use commands like this to pass various sorts of data streams to various programs. But that's not the way the Python sql API (or most language-specific) sql APIs works.
You need to pass a valid SQL query to the execute() method in the API, so the API can pass it to the database server. A vaild query will be something like INSERT or CREATE TABLE.
Look, the server might be on a different host machine, so telling the server to read from /mypath/test.sql is very likely a meaningless instruction to that server. Even if it did understand it, it might say File test.sql not found.
The mysql(1) command line client software package can read commands from files. Is that what you want?
>>> import MySQLdb
>>> db = MySQLdb.connect(host = 'demodb', user = 'root', passwd = 'root', db = 'mydb')
>>> cur = db.cursor()
>>> cur.execute('select * from mytable')
>>> rows = cur.fetchall()
Install MySQL-Python package to use MySQLdb.

MySQL in Python

The purpose is to check if the email already exists in the database utilizing python and MySQLdb. I am using the variable mail to store the e-mail. The MySQL form is email. I have the code below:
if cursor.execute("select count(*) from registrants where email = " + "'"email2"'") == 0:
print "it doesn't exist!"
What is wrong with this statement or how can I go about doing this?
I hardly know where to start.
Just typing a string of SQL into a Python program doesn't somehow query the database. You actually have to open a database connection, instantiate a cursor, use that cursor to run the SQL, and fetch the result. All this is explained in the MySQLdb documentation.
Once you've done that, you'll still need to actually pass the email parameter from your form to the SQL statement, which you're not doing either.
well that won't work because that's just the mysql query string. You have to execute this query using a mysql client receive the results and the test. Using pymysql would be something like this:
import pymysql
connection = pymysql.connect(host,user,password,database)
cursor = connection.cursor()
cursor.execute("select count(*) from registrants where email = ?") #you need to replace the ? with some actual value or the query will fail
result = cur.fetchone()
if result[0]==0:
print "E-mail does not exist!"

Categories

Resources