Python SQLite Update Function not working - python

I'm using Python 3.7.5 and SQLite3 3.X as well as Tkinter (but that's irrelevant) and I can't seem to update my table called "Account"
try:
Cursor.execute("""CREATE TABLE Account (
Application text,
Username text,
Password text)""")
except sqlite3.OperationalError:
Cursor.execute("""UPDATE Account SET
Application = :NewApp,
Username = :NewUser,
Password = :NewPass
WHERE oid = :oid""",
{"NewApp": NewApplicationE.get(),
"NewUser": NewUsernameE.get(),
"NewPass": NewPasswordE.get(),
"oid": X[3]
})
The try bit is just to create the table if there's not already one and if there is it goes on to update the table
I know for a fact there's columns called Application, Username, Password and the variable.get() all returns the proper string
The oid being X[3] gives you an integer
The program runs but it doesn't actually seem to update anything.
Any help with the formatting or just in general would be appreciated

I think that you need just commit your change
I assume that you get cursor from a connectio,
For instance something like that should work:
import sqlite3
conn = sqlite3.connect('example.db')c = conn.cursor()
Cursor = conn.cursor()
try:
Cursor.execute("""CREATE TABLE Account (
Application text,
Username text,
Password text)""")
conn.commit()
except sqlite3.OperationalError:
Cursor.execute("""UPDATE Account SET
Application = :NewApp,
Username = :NewUser,
Password = :NewPass
WHERE oid = :oid""",
{"NewApp": NewApplicationE.get(),
"NewUser": NewUsernameE.get(),
"NewPass": NewPasswordE.get(),
"oid": X[3]
})
conn.commit()
conn.close()
Referece
https://docs.python.org/3/library/sqlite3.html

Related

Tuple decryption problem using cryptography.fernet

ok so I'm trying to code a password manager in python and I'm using cyrptography.fernet to crypt the emails and passwords and then store them into a local SQLite database the problem is that when I try to get for example the emails in the database they are in this format: (b'encypted-email-here'), (b'and-so-on) so I thought since theres the b before the quotes it's in bytes format and I do not need to do anything in order to decrypt them but when I actually try to decrypt them I get an error saying: "TypeError: token must be bytes" here is my code so you can take a look at it
b_email = email.encode('utf-8')
b_pwd = pwd.encode('utf-8')
enc_email = f.encrypt(b_email)
enc_pwd = f.encrypt(b_pwd)
conn = sqlite3.connect('database.db')
execute = conn.cursor()
execute.execute('CREATE TABLE IF NOT EXISTS logins (website, email, password)')
execute.execute('INSERT INTO logins VALUES (:website, :email, :password)', {'website': website, 'email': enc_email, 'password': enc_pwd})
conn.commit()
conn.close()
def view():
con = sqlite3.connect('database.db')
cur = con.cursor()
iterable = cur.execute('SELECT email FROM logins')
for email in iterable:
dec_email = f.decrypt(email)
print(dec_email)```
cur.execute() returns a sequence of rows, each of them is a tuple. In your case, a tuple of just one element, but still you need to extract the email from it. The most elegant way would be unpacking (notice the comma after email):
for email, in cur.execute('SELECT email FROM logins'):
print(f.decrypt(email))

Register-Login system

I am trying to make a register-login system in Python 3, but when I check if the Email address already exists or not, it always says that it doesn't. I inserted an email and a password in the "users" table and when asked I used that same email address in this script but it still says that it doesn't exist. I have little to none experience in MySQL and thought that this may be a nice project to start with. Thank you.
import cymysql
from getpass import getpass
def get_user_info():
while True:
email = input("Input your Email address (max. 64 chars.): ")
password = getpass("Input a password (max. 64 chars.): ")
if len(email) < 64 and len(password) < 64:
return email, password
def check_account(cur, email, password):
if(cur.execute(f"SELECT * FROM `users` WHERE `Email`='{email}' LIMIT 1")):
print("exist")
else:
print("no exist")
def main():
conn = cymysql.connect(
host='192.168.0.109',
user='root',
passwd='',
db='database'
)
cur = conn.cursor()
email = ''
password = ''
email, password = get_user_info()
check_account(cur, email, password)
cur.close()
conn.close()
if __name__ == '__main__':
main()
Disclaimer: I have yet to use cymysql – any code attached below is untested.
First, note that CyMySQL is a forked project of PyMySQL[1] so I will refer to documentation from PyMySQL.
From pymysql.cursors.Cursor.execute documentation:
execute(query, args=None)
Execute a query
Parameters:
query (str) – Query to execute.
args (tuple, list or dict) – parameters used with query. (optional)
Returns: Number of affected rows
Return type: int
The important thing to consider is the execute function returns: the number of affected rows. A SELECT query will not affect any rows, thus the function will return 0 and your function will print no exist reasonably.
Use fetchone to check that at least one row was returned.
def check_account(cur, email, password):
cur.execute(f"SELECT * FROM `users` WHERE `email`=%s LIMIT 1", (email,))
row = cur.fetchone()
if row:
print("exist")
else:
print("no exist")
(I rewrote your cur.execute call in consideration of my earlier comment.)

SQLite not accepting unique command

Python/Flask:
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS users (email TEXT NOT NULL UNIQUE, password TEXT)')
print('Table created')
Then in another method
def create_user(email, hashedpw):
try:
cur.execute('INSERT INTO users VALUES (?, ?)', (email, hashedpw))
conn.commit()
return "works"
except:
print(str(sqlite3.Error))
return None
Even if I input the same email 10 times it still records the data in the database and doesn't give an error. I clearly set it to UNIQUE then why isnt it working?
Your syntax looks good so only explanation that comes to mind is:
You already have a table named users in your database which doesn't have the UNIQUE constraint and since you are using IF NOT EXISTS, that table remains as it is.

use if condition to compare the password using python

I have HTML form for getting the name and the password .And python codes are used to get that enter data and store in variable first_name and password.
For given name stored password is fetched from database using WHERE clause .
By using if condition I have tried to compare the password fetched from database and password entered from form.If they are equal then do some action .If not do some other condition .But the problem is i am not able to understand how to assign the if condition .
What i tried is as given below.:
#!"C:\python34\python.exe"
import cgitb ,cgi
import sys
import mysql.connector
cgitb.enable()
form = cgi.FieldStorage()
print("Content-Type: text/html;charset=utf-8")
print()
# Get data from fields
first_name = form.getvalue('first_name')
password = form.getvalue('pass')
print (password)
conn = mysql.connector.connect(host='localhost',port='8051',
database='test',
user='root',
password='next')
cursor = conn.cursor()
if conn.is_connected():
print('Connected to MySQL database')
cursor.execute("""SELECT pass FROM tablename1 where name = '%s'""" % (first_name))
for row in cursor():
if(password == row):
print("sucess")
else:
print("fail")
Please check my code.And give some suggestion.
When a user registers for the first time, you should save his password like this:
$password = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
This should output something like $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
And you should store it in your database.
Then you should verify passwords like this:
<?php
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq'; // you get it from your database
if (password_verify('rasmuslerdorf', $hash)) { // 'rasmuslerdorf' is what user entered
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
Now, what is a hash? Please read this.
EDIT: you mean something like this?
cursor.execute("SELECT * FROM users WHERE username= ? and password= ?",
(username, pass1))
found = cursor.fetchone()
if found:
# user exists and password matches
else:
# user does not exist or password does not match

How can I prevent insertion conflict when inserting a variable to a sqlite table?

Hey I'm okay with writing to the table, except unable to check of the data is already there and if the data is then don't write the data and print a value saying that it already exists.
Here is what I have so far
def createAccount():
username = raw_input("username: ")
password = raw_input("password: ")
c.execute("INSERT INTO Logindetails(Username, Password) VALUES (?,?)",
(username, password,))
conn.commit()
Thanks if you can help me, its for my coursework and I'm pretty new to all this.
If you change the create table statement to the following, sqlite will know that each username must be unique because you're defining a 'PRIMARY KEY', one that must be unique:
c.execute("""CREATE TABLE LoginDetails
(Username text PRIMARY KEY, Password text)""")
If you then attempt to insert a row into the table with an existing username, an integrity error will occur:
IntegrityError: column username is not unique
You can catch this (and other errors similarly) using a try, except clause as follows (this assumes you're using sqlite3):
try:
c.execute("INSERT INTO Logindetails(Username, Password) VALUES (?,?)",(username, password,))
except sqlite3.IntegrityError:
print("Username already exists!")

Categories

Resources