Why is fetchone() returning none here? [duplicate] - python

This question already has answers here:
MySQL/Python -> Wrong Syntax for Placeholder in Statements?
(1 answer)
Why can't replace placeholder with format function in pymysql?
(3 answers)
Closed 2 years ago.
Why does the fetchone() return None when onLogin() is called, even though the database has a row with a value?
When I use the same query in the sql database it returns the correct value.
Using fetchall() and using a for loop with it returns nothing on the terminal.
import mysql.connector
#SQL CONNECTION
db = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="python"
)
cursor = db.cursor(buffered=True)
#main
def onStart():
global username
print("Enter a username to continue")
username = input()
#Checking the database for the username
query = "SELECT username FROM userdata"
cursor.execute(query)
result = cursor.fetchall()
for x in result:
if x == (username,):
onLogin()
else:
print("Error Occurred!")
def onLogin():
print("Enter a password")
password = input()
#comparing pwds
query = "SELECT password FROM userdata WHERE username = '%s'"
cursor.execute(query, username)
result = cursor.fetchone()
print(result)
onStart()

As deceze said, you shouldn't quote the '%s' placeholder in the prepared query.
In addition, you should avoid doing getting every single user in your database just to figure out if this one exists - and while you're at it, you can get the password in the same query and just compare it in your program. (Naturally in a real-life situation you'd use a password derivation function and not store cleartext passwords in the database.)
import mysql.connector
# SQL CONNECTION
db = mysql.connector.connect(
host="localhost", user="root", password="", database="python"
)
cursor = db.cursor(buffered=True)
def authenticate():
username = input("Enter a username to continue")
cursor.execute(
"SELECT username, password FROM userdata WHERE username = %s LIMIT 1",
(username,),
)
result = cursor.fetchone()
if not result:
print("No such user.")
return None
username, correct_password = result
password = input("Enter a password")
if password == correct_password:
print("Access granted!")
return username
username = authenticate()
# If `username` is none, authentication failed

Related

How to use flask variable in calling SELECT query in MariaDB

What is the correct syntax for calling a SELECT query in MariaDB from a Registration Form.
Specifically, in the WHERE clause. I've been looking all over the net to debug this and it does not seem to work (semantically).
Here is the code in my python flask.
#app.route('/check_email', methods = ['POST', 'GET'])
def chck_Email():
if request.method == 'POST':
visEmail = request.form['email']
conn = mariadb.connect(**config)
print(f"WE ARE CONNECTED ORAYT")
# create a connection cursor
cur = conn.cursor()
# execute an SQL statement
try:
print(visEmail)
#sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name) VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
current_Email= cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
print(current_Email)
if current_Email != None:
print('Email Invalid: Email already exists!')
form = Registration_Form()
exists = {
"email_exists": True
}
return render_template(exists,'register.html', form = form )
""The visEmail is the variable that is supposed to be holding the email address given by the user upon clicking submit, the program then checks in the database if the given email address already exists in the DB.
I printed the data in the visEmail variable to see the string(Which is fine), but the execution in the database returns me with "None" (It should not be returning a None since I already have the given email address on the DB). It is supposed to return the error "Email Already exists"
THank you very much
You're not fetching the row of results. cur.execute() doesn't return anything, you have to call cur.fetchone() to get the results, and assign that to current_Email.
try:
print(visEmail)
#sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name) VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
current_Email = cur.fetchone()
print(current_Email)
if current_Email != None:
print('Email Invalid: Email already exists!')
form = Registration_Form()
exists = {
"email_exists": True
}
return render_template(exists,'register.html', form = form )

cur.fetchone()[0] is all of a sudden a Nonetype

Im making a login system as a data base Im using SQLite.
def loginfunction(self):
user = self.emailfield.text()
password = self.passwordfield.text()
if len(user)==0 or len(password)==0:
self.error.setText("Please input all fields.")
else:
conn = sqlite3.connect("shop_data.db")
cur = conn.cursor()
query = 'SELECT password FROM login_info WHERE username =\''+user+"\'"
cur.execute(query)
result_pass = cur.fetchone()[0]
if result_pass == password:
print("Successfully logged in.")
self.error.setText("")
else:
self.error.setText("Invalid username or password")
When I run it if the password does not match with the username from the data base it works but if I type a wrong username the app closes and prints out this
main.py", line 38, in loginfunction
result_pass = cur.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable
Here is what SQLite log says + what the data base looks like data base
fetchone does
Fetches the next row of a query result set, returning a single
sequence, or None when no more data is available.
For any
'SELECT password FROM login_info WHERE username =\''+user+"\'"
there is not matching row in data if user provided username not present in username column. You should do something like
query_result = cur.fetchone()
if result_pass is None:
print("Username with given name is not known")
# action to undertake in such case
result_pass = query_result[0]
then continue as earlier

How would I make my code which creates accounts safe from SQL-Injections?

This is my code:
import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS accounts(name text primary key, password text)')
connection.commit()
connection.close()
continue_loop = True
yes_no_value = input("Would you like to create a new account? (yes/no): ")
if yes_no_value == 'no':
continue_loop = False
while continue_loop:
user = input("Enter username: ")
password = input("Enter password: ")
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute(f'INSERT INTO accounts VALUES("{user}", "{password}")')
connection.commit()
connection.close()
print('success')
yes_no_value = input("Would you like to create a new account? (yes/no): ")
if yes_no_value == 'no':
continue_loop == False
It would help if someone could send me my code but edited to be safe from SQL injections, and explain.
In the code you provided, the code that's at risk from injection is this line:
cursor.execute(f'INSERT INTO accounts VALUES("{user}", "{password}")')
So, what you have to worry about is the safety of the values of user and password at that point. You're allowing the user to enter them from the console, so they could basically enter anything.
You could instead:
cursor.execute(f'INSERT INTO accounts VALUES(?, ?)', (user, password))
This has the same result, but now cursor.execute() (or an underlying call) turns the values of user and password into the values for SQL and has a chance of catching shenanigans in the process.

Want to insert data in MYSQL table by user command using python programming [duplicate]

This question already has answers here:
How can I insert data into a MySQL database?
(3 answers)
Closed 3 years ago.
I want to insert data in mysql table by user command. But i can't understand why cannot execute code. Code sample:
user_name= input("What is your name?:\n")
user_phone= input("What is your phone:\n")
user_city= input("Your city:\n")
myCursor.execute("insert into information(name,phone, city) values(user_name, user_phone, user_city);")
print("Insert successfully")
import pymysql
con = pymysql.connect("Host", "Username", "Password", "Database")
cur = con.cursor()
#taken from sample displayed
user_name = input("What is your name?:\n")
user_phone = int(input("What is your phone number:\n"))
user_city = input("Your city:\n")
cur.execute("insert into information(name,phone, city) values('{}', {},
'{}')".format(user_name, user_phone, user_city))
con.commit()
con.close()
you need to define below variables in order to use execute.
import cx_Oracle
DSN_TNS = cx_Oracle.makedsn(IP, PORT, SID)
DB_CRED = cx_Oracle.connect(USERNAME, PASSWORD, DSN_TNS)
curs = DB_CRED.cursor()
user_name= input("What is your name?:\n")
user_phone= input("What is your phone:\n")
user_city= input("Your city:\n")
sql_query = "insert into information(name,phone, city) values('{0}','{1}','{2}')".format(user_name, user_phone, user_city)
curs.execute(sql_query)
DB_CRED.commit()
DB_CRED.close()

Why is my .fetchone function returning "none"?

Username is a variable that is drawn from an Entrybox using tkinter. I need for dbsalt to return the outcome of the cursor1.execute query as a string, but it returns "none" or presents a traceback that states "NoneType has no attribute getitem". I do not understand what is incorrect.
def login_verification(self):
sql = ("SELECT salt FROM User WHERE username = %s")
username = self.KUEntry.get()
print username
cursor1.execute(sql, username)
dbsalt = cursor1.fetchone() [0]
print dbsalt
sql2 = ("SELECT PashHash FROM User WHERE username = %s")
cursor2.execute(sql2, username)
dbhash = cursor2.fetchone() [0]
print dbhash
test = hashlib.sha512(username + dbsalt).hexdigest()
print test
if test == dbhash:
self.intro_screen
else:
print "incorrect password"
You didn't call execute method, but assigned to it. Call it using cursor.execute(..):
And you should use ' to quote the string.
username = self.KUEntry.get()
cursor1.execute("SELECT salt FROM User WHERE username = '%s'" % username)
dbsalt = str(cursor1.fetchone())
print dbsalt
BTW, it is better to use parameter passing style than manually formatting string to prevent SQL injection.
cursor1.execute("SELECT salt FROM User WHERE username = %s", [username])

Categories