I want to retrieve the data to match values - python

I want to retrieve the data to match username and password. So I try this but it doesn't work
Here my code in views.py
username = request.POST['username']
password = request.POST['password']
conn = mariadb.connect(host="localhost",user="django",password="1234",database="mydatabase")
cur = conn.cursor()
res = cur.execute("SELECT user_username FROM store_users WHERE user_username = username")
conn2 = mariadb.connect(host="localhost",user="django",password="1234",database="mydatabase")
cur2 = conn2.cursor()
res2 = cur2.execute("SELECT user_password FROM store_users WHERE user_password = password")
if res is not None and res2 is not None:
return render(request,'index.html')
else:
messages.error(request,"Username หรือ Password ไม่ถูกต้อง")
return redirect("/login")

you should use F-strings for your queries:
F"SELECT user_username FROM store_users WHERE user_username = {username}"

Related

TypeError: argument 1 must be str, not tuple

I received this error when trying to select columns from an SQLite3 DB, where the column 'Username' was the same as the variable 'username' and the column 'Password' was the same as the variable 'EncMessage' (Both the password and username was inputted by a user through a Tkinter entry box.
When I ran the program and inputted a valid username and password into the entry boxes, I received this error 'line 3139, in signin
c.execute(("SELECT Username, Password FROM Customers WHERE Username = ? AND Password = ?", username, encMessage,))
TypeError: argument 1 must be str, not tuple'
Any help would be appreciated.
# SignIn Function
def signin():
username = user.get()
password = pass.get()
check_pass = password
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*#?&])[A-Za-z\d#$!#%*?&]{6,20}$"
# Compiling regex
pat = re.compile(reg)
# Searching regex
mat = re.search(pat,password)
# Validation conditions
if mat and password == check_pass:
message = password
key = Fernet.generate_key()
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
decMessage = fernet.decrypt(encMessage).decode()
if check_pass == decMessage:
conn = sqlite3.connect('CustomersTTA.db')
# Create a cursor instance
c = conn.cursor()
c.execute("Select rowid, * FROM Customer")
records = c.fetchall()
c.execute(("SELECT Username,Password FROM Customers WHERE Username = ? AND Password = ?", username, encMessage,))
if not c.fetchone():
messagebox.showerror("Invalid","Credentials are incorrect")
else:
print("Welcome")
c.execute(("SELECT Username,Password FROM Customers WHERE Username = ? AND Password = ?", username, encMessage,))
has double parenthesis, remove 1 layer.
Edit: Next time you ask questions, provide full traceback and tell us which line is it. You are making helping you harder than it should be.

Get value of row from mysqlphp in flask python

I have table like:
Database
I want to print password only like:
samer
I tried this:
mysql = MySQL()
flask.config['MYSQL_HOST'] = 'localhost'
flask.config['MYSQL_USER'] = 'root'
flask.config['MYSQL_PASSWORD'] = ''
flask.config['MYSQL_DB'] = 'web'
mysql.init_app(flask)
#flask.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
# print(password)
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SELECT * FROM users WHERE password=%s', (password,))
user = cur.fetchall()
print(user)
# if password is wrong, user will be None else Dict
if user is not None:
print(user['password'])
else:
print("User not found")
but i get this error:
TypeError: tuple indices must be integers or slices, not str
i can print result if i use:
for row in user:
passw = row['password']
but i need to use first method, how can i achieve that?
You need to replace the fetchall call with fetchone:
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SELECT * FROM users WHERE password=%s', (password,))
user = cur.fetchone()
# if password is wrong, user will be None else Dict
if user is not None:
print(user['password'])
else:
print("User not found")

how to authenticate logins in python tkinter?

hi I want to check the exact password for a particular username in a database,what can I do
def login():
conn = sqlite3.connect("test.db")
cur = conn.cursor()
un = E_Username.get()
pw = E_Password.get()
cur.execute("SELECT username,password FROM users")
# build a set with all names, from the results given as [('name1',), ('name2',), ('name3',)]
names = {username[0] for username in cur.fetchall()}
key = {password[0] for password in cur.fetchall()}
You have to use WHERE statement to fetch password from database
cur.execute("SELECT password FROM users WHERE username=?", (un,))

ValueError: Could not process parameters in Python/MySQL

I want to prevent duplicate usernames when people register.
Here is my code snippet:
def submit(self):
username_info = username.get()
username_password = password.get()
#connect to db
db = mysql.connector.connect(host = 'localhost', user = 'root', password = '', database = 'user')
#create a cursor
mycursor = db.cursor()
#insert to db
sql = ("INSERT INTO useraccess (user_type, password) VALUES (%s, %s)")
query = (username_info, username_password)
mycursor.execute(sql, query)
#commit
db.commit()
#create a messagebox
messagebox.showinfo("Registration", "Successfully Register")
#if username has been used
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
user_query = (username_info)
mycursor.execute(find_user, user_query)
#if (username == username_info):
if mycursor.fetchall():
messagebox.showerror("Registration", "The username chosen is already used. Please select another username")
else:
messagebox.showinfo("Registration", "Account Created!")
But every time I run it, although the username has been registered in the db, it only shows the successfully created messagebox and error:
ValueError: Could not process parameters.
Anyone can help me to solve this problem?
I believe the source of the problem is in the line
user_query = (username_info)
It should be
user_query = (username_info,)
The trailing comma is the syntactic difference between an expression in parentheses and a tuple.
Another issue with code is the query:
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
Which should be:
find_user = ("SELECT * FROM useraccess WHERE user_type = %s")
Have you checked these variables,
username_info = username.get()
username_password = password.get()
are they in proccesable formats? (i.e. can you directly put the username.get() into user_type ?)
I'm not familiar with this way of passing a parameter
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
have you double checked this? (why not the %s method?)
also, you probably get the "Account Created!" because mycursor.fetchall() fails.

Why is my web application generating a 1064 (42000) error when trying to POST an INSERT query? [duplicate]

This question already has answers here:
How to create a "singleton" tuple with only one element
(4 answers)
Closed 6 years ago.
I'm trying to create a user registration page using Flask, MySQL and HTML forms. I'm running into this error when I try to post data from the form to the database. Can anyone see where I might have gone wrong with the SQL?
The full error received is:
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
My connection function is:
import mysql.connector
from flask import *
def connection():
conn = mysql.connector.connect(host="localhost", db="user_login",user="root",
password="password")
c = conn.cursor()
return c, conn
This is imported in the init.py file and called below:
class RegistrationForm(Form):
firstName = StringField('First Name', [validators.Length(min = 3, max = 25)])
lastName = StringField('Surname', [validators.Length(min = 3, max = 25)])
username = StringField('Username', [validators.Length(min = 4, max = 25)])
email = StringField('Email Address', [validators.Length(min = 6, max = 50)])
password = PasswordField('Password', [validators.required(),
validators.EqualTo('confirm', message = 'Passwords must match')])
confirm = PasswordField('Repeat Password')
#app.route('/register/', methods = ['GET', 'POST'])
def register_page():
try:
form = RegistrationForm(request.form)
if request.method == "POST" and form.validate():
firstName = form.firstName.data
lastName = form.lastName.data
username = form.username.data
email = form.email.data
password = form.password.data
is_admin = 0
c, conn = connection()
x = c.execute("SELECT * FROM users WHERE username = %s",(username))
if int(x) > 0:
flash("That username is already taken, please choose another")
return render_template('register.html', form = form)
else:
c.execute("""
INSERT INTO users (firstName, lastName, username, email, password, is_admin)
VALUES (%s, %s, %s, %s, %s, %s)
""",(firstName, lastName, username, email, password, is_admin))
conn.commit()
flash("Thanks for registering!")
c.close()
conn.close()
gc.collect()
session['logged_in'] = True
session['username'] = username
return redirect(url_for('dashboard'))
return render_template('register.html', form = form)
except Exception as e:
return(str(e))
I think your issue is the SELECT, not the INSERT. You are passing (username) as a parameter -- this is not a tuple. You need to use a trailing comma:
x = c.execute("SELECT * FROM users WHERE username = %s", (username,))

Categories

Resources