How to check for multiple data when deleting a row - python

I want to delete a row using Python with MySQL but when I delete it I have to use this command:
cursor.execute("DELETE FROM users WHERE username= jazzar")
But I want to check for multiple things like the email and password

You can use multiple conditions in query.
cursor.execute("DELETE FROM users WHERE username = jazzar AND email = jazzar#example.com AND password = YOUR_PASSWORD")

Related

Updating a Table by using Sqlite3 Module in Python

I am working on a project where i need to update the password column of a user table pointing userid as the primary key, whenever the user reset his/her password. I am passing username and password to update_table function based on the values entered by the user from console and below is my code snippet -
def sql_update_table(conn, username, reset_password):
c = conn.cursor()
#value = (username, reset_password)
#c.execute('''UPDATE user SET password = ? WHERE userid = ? ''', value)
c.execute('''UPDATE user SET password = reset_password WHERE userid = username''')
conn.commit()
I tried both case passing values with a tuple as mentioned in # and directly as mentioned without a #. However, for first case, there is no error but the table is not getting updated with the new value of password and for later one i am getting below error -
sqlite3.OperationalError: no such column: reset_password
Please help me to solve this.
Thanks in advance !
Can you please try replacing
c.execute('''UPDATE user SET password = reset_password WHERE userid = username''')
with
c.execute('''UPDATE user SET password = ? WHERE userid = ? ''', (username,reset_password))

Accessing specific item in sqlite3 database when user and password matches

I've created a login GUI with sqlite in python and i've got it working correctly, however I want it to do something else as well when it logs in.
My sqlite database currently has the following columns;
Username, Email, Password, Workstation, Directory
I've found that you can take an item string in the table by using something like;
connection.fetchall()[index]
However, I don't know how to implement it into my code to check for the user that logged in.
username = "username"
password = "password"
# database information
connection = sqlite3.connect(databasepath+'\login.db')
result = connection.execute("SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?", (username, password))
if (len(result.fetchall()) > 0):
#some code#
I want to access the 'Directory' item for the user that logged in

locating a password that corresponds to a username within an sqlite table

I am running a website using Flask microframework and sqlite3 to store user logins. Currently, I am having trouble with matching the username and password entered by the user from an HTML form, with the existing records within my database.
I am using the flask-login extension to help me with this, and when I try and match, I am receiving a TypeError:
list indices must be integers or slices, not str
here is my python code that is turning the SQLite table into a variable:
con = sql.connect("table.db")
cur = con.cursor()
cur.execute('SELECT * FROM users')
names = cur.fetchall()
I then have this code which is taking the password from the HTML form, and trying to match it with the password linked to the username in the table
user_name = request.form['username']
if request.form['password'] == names[user_name]['password']:
user = User()
user.id = user_name
flask_login.login_user(user)
this is what 'names' returns:
[(7, 'ValidName', 'ValidTest', 'User#test.com'), (8, 'User2', 'password2', 'User#test2.com')]
What needs to happen is the program will check the form input for 'password' and will match it with the 'password' that is related to the username. So as an example, if ValidName and ValidTest were entered into the form, they would be requested by the program, and matched with the records found in 'names'.
I assume you have not hashed your password which is something you should do. Without security in mind
here is my dirty approach
cur.execute('SELECT * FROM users WHERE name = %s AND password = %s', (request.form['username'], request.form['password']))
user = cur.fetchone()
This can be helpful
Here is the guilty: names[user_name]['password']
names is the return value of fetchall and hence is a plain list. To use it in above expression, it should be a mapping of mappings.
You should construct it that way:
names = {row[1]: {'id': row[0], 'password': row[2], 'mail': row[3]}
for row in cur.fetchall()}
But beware: this loads the full user database in memory. It only makes sense if you have few users...

Selecting data from multiple tables that have no foreign keys?

I have this current sqlite3 code in my python file:
Data = Cursor.execute("""
SELECT Username, Password
FROM PatientTable
WHERE Username = '{}'
""".format(Username))
Data = Data.fetchall()
There are multiple tables in the database: PatientTable, DoctorTable, ManagerTable. Each one has attributes of Username and Password in the second and third column respectively.
Q: My current code only selects data from PatientTable but I need to select data from all three tables and identify which table each item of data came from.
Now, I think I can do this using multiple SQL statements but this seems excessive. I have thought about using JOIN but there are no foreign keys - keys relating the databases to each other.
Thanks in advance.
You seem to be looking for UNION. You can add a fixed column to each query to distinguish from which table each record in the resultset comes from :
SELECT 'PatientTable' source_table, Username, Password
FROM PatientTable
WHERE Username = '{}'
UNION ALL SELECT 'DoctorTable' , Username, Password
FROM DoctorTable
WHERE Username = '{}'
UNION ALL SELECT 'ManagerTable', Username, Password
FROM ManagerTable
WHERE Username = '{}'

SQL Query returning "None" instead of row

I'm working on a light login, and have a tabled titled Users. I'm trying to take my login form POST body and verify it across the database.
Values from form:
user = request.form['username']
password = request.form['password']
SQL Statement:
conn = sqlite3.connect(db)
cur = conn.cursor()
cur.execute("SELECT * FROM Users WHERE Username LIKE '(%s)'" % user)
row = cur.fetchone()
Users Table:
So on a POST request from my form, here is what is printed:
Print(user, password) = ph104694 Password123
Print(row) = None
So you can see the row is being returned as None when the data absolutely exists. If I change user to something I know is incorrect, I'm getting the same results, but if I change the table from Users to something like Users2 I'm met with a no table exists error which is fine. So despite matching data existing something about my statement isn't allowing it to produce that row. Any ideas?
You're search expression is evaluating to (ph104694) which clearly doesn't exist in the data you showed.
There is no reason to use the LIKE operator here and it probably runs counter to what you want to do (match the single record exactly matching the user ID that was entered).
This is the classic example of code that is subject to an SQL injection attack. You should never, never, ever use string interpolation to build an SQL string like this. Instead, use parameter substitution.
Taken all together, you want something like this:
cur.execute("SELECT * FROM Users WHERE Username = ?", [user])
Your query string evaluates to "SELECT * FROM Users WHERE Username LIKE '(ph104694)'".
Note the parentheses which aren't in the actual username.
Also, you almost certainly don't want to use LIKE.
What you want is "SELECT * FROM Users WHERE Username = 'ph104694'"
Which would create with "SELECT * FROM Users WHERE Username = '{user}'".format(user=user)
Also, you can (and should) parameterize this as
cur.execute("SELECT * FROM Users WHERE Username = :user", {user: user})

Categories

Resources