Why is my code locking the database? SQLite and Python - python

import sqlite3
conn = sqlite3.connect('/Users/macbook/Desktop/lool.db')
c = conn.cursor()
invalid_input = True
def startinglogin(self):
loginmessage = input("To register to the Quizzer, type in 'Register'. To login, type in 'Login'.\n")
while loginmessage != "Login" and loginmessage != "Register":
loginmessage = input("To register to the Quizzer, type in 'Register'. To login, type in 'Login'.\n")
self.loginmessage = loginmessage
studentusername = ' '
studentpassword = ' '
def nameandpass():
global studentusername
studentusername = input('Enter username: ')
global studentpassword
studentpassword = input('Enter password: ')
def start():
def passlength():
while len(studentpassword) < 4 or len(studentpassword) > 16:
print ("ERROR. Your password must be longer than 4 characters and shorter than 16 characters.")
studentpassword = input('Enter password: ')
def usernamechecker():
c.execute("SELECT username FROM studenttest WHERE username=(?)", (studentusername, ))
if c.fetchone() == None:
global usernamecheck
usernamecheck = ' '
else:
c.execute("SELECT username FROM studenttest WHERE username=(?)", (studentusername, ))
usernamecheck = ' '.join(map(str, (c.fetchone())))
def passwordchecker():
c.execute("SELECT password FROM studenttest WHERE password=(?)", (studentpassword, ))
if c.fetchone() == None:
global passcheck
passcheck = ' '
else:
c.execute("SELECT password FROM studenttest WHERE password=(?)", (studentpassword, ))
passcheck = ' '.join(map(str, (c.fetchone())))
def create_db():
c.execute("DROP TABLE IF EXISTS studenttest")
c.execute("CREATE TABLE studenttest (id INTEGER PRIMARY KEY, username TEXT, password TEXT)")
conn.commit()
def loginform():
while usernamecheck != studentusername or passcheck != studentpassword:
print ("Your login info is wrong.")
nameandpass()
usernamechecker()
passwordchecker()
if usernamecheck == studentusername and passcheck == studentpassword:
print ("Access granted!")
global invalid_input
invalid_input = False
else:
print("Access denied!")
def registerform():
while studentusername == useravailable:
print ("That username is already taken!")
global studentusername
studentusername = input("Enter username: ")
if studentusername != useravailable:
c.execute("INSERT INTO studenttest VALUES (NULL,?,?);", (studentusername, studentpassword))
global invalid_input
invalid_input = False
conn.commit()
def sameusername():
c.execute("SELECT username FROM studenttest")
global useravailable
useravailable = ' '.join(map(str, (c.fetchone())))
if startinglogin.loginmessage == "Register":
sameusername()
registerform()
elif startinglogin.loginmessage == "Login":
usernamechecker()
passwordchecker()
loginform()
conn.commit()
while invalid_input:
startinglogin(startinglogin)
nameandpass()
start()
if invalid_input == False:
c.close()
I have no idea why my code is locking the database, can someone help out with that? The error message that is displayed in the shell is:
Traceback (most recent call last):
File "/Users/macbook/Documents/hey draft2.py", line 85, in <module>
start()
File "/Users/macbook/Documents/hey draft2.py", line 75, in start
registerform()
File "/Users/macbook/Documents/hey draft2.py", line 65, in registerform
c.execute("INSERT INTO studenttest VALUES (NULL,?,?);", (studentusername, studentpassword))
sqlite3.OperationalError: database is locked
If this is a noob mistake, I'm really sorry for wasting time. :/
EDIT: Forgot to call passlength() in the code, don't mind that. Adding or taking it out had no effect.

Would you happen to be using a visual tool for sqlite (e.g. sqlitebrowser) while running your code? If you have unwritten changes in the visual tool it might throw errors if you try to run your python code. The fix is to write the changes, then try the code again.
EDIT: This question has an answer that recommends this old sqlite documentation, that might help too.

Related

Error when checking if username, hash, and key exists in a table stored in mysql

The output of the program:
WELCOME, PLEASE ENTER YOUR USERNAME AND PASSWORD
Enter username:Manas
Enter password:123456
error2
Error3
Below is a minimal code of the program:
import mysql.connector
import hashlib
import os
mycon=mysql.connector.connect(host="localhost",user="root",passwd="123456",database="library",use_unicode=True,charset="utf8")
cursor=mycon.cursor()
stmt = "SHOW TABLES LIKE 'users'"
cursor.execute(stmt)
result = cursor.fetchone()
if result:
pass
else:
cursor.execute("create table users(username varchar(20),key varbinary(100),salt varbinary(100));")
def users(username,password):
cursor.execute("select * from users where username='{}'".format(username))
data=cursor.fetchone()
if data=="(NULL)":
return False
elif data==True:
salt=data[2]
key=hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
if data[1]==key:
return True
elif data[1]!=key:
return False
else:
print("error1")
else:
print("error2")
return False
#Main program
print("WELCOME, PLEASE ENTER YOUR USERNAME AND PASSWORD")
username=input("Enter username:")
password=input("Enter password:")
users(username,password)
if users==True:
print("user exists")
elif users==False:
print("user does not exist")
else:
print("Error3")
The table it was being referred to:
mysql> use library;
Database changed
mysql> select * from users;
+----------+--------------------------------------------------------------------+--------------------------------------------------------------------+
| username | key | salt |
+----------+--------------------------------------------------------------------+--------------------------------------------------------------------+
| Manas | 0xE42AB9B18A8F144EA7933FFA8E69E1FE28F20DA67B3E0FF3F1A0C2203D6148B2 | 0xF68894D924A69D035CC096C497F933B29A08E075F6DA2B19D955D08A33C0CAB4 |
+----------+--------------------------------------------------------------------+--------------------------------------------------------------------+
1 row in set (0.00 sec)
Print(Data):
WELCOME, PLEASE ENTER YOUR USERNAME AND PASSWORD
Enter username:Manas
Enter password:12345
('Manas', bytearray(b'\xe4*\xb9\xb1\x8a\x8f\x14N\xa7\x93?\xfa\x8ei\xe1\xfe(\xf2\r\xa6{>\x0f\xf3\xf1\xa0\xc2 =aH\xb2'), bytearray(b'\xf6\x88\x94\xd9$\xa6\x9d\x03\\\xc0\x96\xc4\x97\xf93\xb2\x9a\x08\xe0u\xf6\xda+\x19\xd9U\xd0\x8a3\xc0\xca\xb4'))
error2
Error3
Why does this happen?
You have to make also the connection so that it uses utf8
Assuming that you have uft8mb4
mycon=mysql.connector.connect(host="localhost"
,user="root"
,passwd="123456"
,database="library"
,charset="utf8mb4")
the character set cpould also be utf8, thqat yoiu have to check
and use prepared statements when hadling parameters
cursor.execute("select * from users where username=%s",(username,))
Update
Addidtional your table definion has a problem key is a reserved word in MySQL so oyu ned to encapsule it in backticks like below
cursor.execute("create table users(username varchar(20),`key` varbinary(100),salt varbinary(100));")
Update 2
after testing your code i found some problems in it
Your function retuns a value ut you never assign it
And the data IS NULL if there are no users
import mysql.connector
import hashlib
import os
mycon=mysql.connector.connect(host="localhost",user="root",passwd="123456",database="library",use_unicode=True,charset="utf8mb4")
cursor=mycon.cursor()
stmt = "SHOW TABLES LIKE 'users'"
cursor.execute(stmt)
result = cursor.fetchone()
if result:
pass
else:
cursor.execute("create table users(username varchar(20),`key` varbinary(100),salt varbinary(100));")
def users(username,password):
cursor.execute("select * from users where username=%s",(username,))
data=cursor.fetchone()
if data is None :
return False
elif data is not None:
salt=data[2]
key=hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
if data[1]==key:
return True
elif data[1]!=key:
return False
else:
print("error1")
else:
print("error2")
return False
#Main program
print("WELCOME, PLEASE ENTER YOUR USERNAME AND PASSWORD")
username=input("Enter username:")
password=input("Enter password:")
users = users(username,password)
if users==True:
print("user exists")
elif users==False:
print("user does not exist")
else:
print("Error3")

How to use a variable's result from one class in another in python?

I'm new to python and I'm working on the following code. Of course this is not the best code but it's currently what I know. Overall, the class Database contains a method called log_in() where we have a variable called login_code. When the user logs in using that method, login_code stores the code that the user enters, after this, the class Logged gets executed and when it runs I want to see what user is logged in from a method called who(). Thank you
class Database:
def clear_console(self):
os.system('cls' if os.name == 'nt' else 'clear')
return self
def txt_menu(self):
self.clear_console()
terms_conditions()
checking = input("> Proceed? ")
if checking == "a":
self.clear_console()
self.user_menu()
else:
self.txt_menu()
def loading_bar(self):
for _ in tqdm(range(101), "> Loading. . .", ncols=75):
time.sleep(0.01)
print("> Complete. . .")
time.sleep(1)
os.system('cls' if os.name == 'nt' else 'clear')
return self
def user_menu(self):
print("")
process = input("> Are you registered y/n? Or forgot details 'f': ")
if process == "y":
self.log_in()
elif process == "n":
self.user_registration()
elif process == "f":
self.forgot_details()
else:
print("Try again! ")
self.user_menu()
def user_registration(self):
global registration_code
cursor = conn.cursor()
print("> To register enter the details below: \n")
registration_username = input("> Username: ")
registration_email = input("> Email: ")
registration_password = input("> Password: ")
for pwd in range(1):
registration_code = ""
for c in range(5):
registration_code += random.choice(chars)
cursor.execute("INSERT INTO tst (username, email, password, code) values (?, ?, ?, ?)",
registration_username, registration_email, registration_password, registration_code)
print("> Your code is: ", registration_code)
print("> Successful registration")
print("")
print("> Welcome", registration_username)
conn.commit()
return
def log_in(self):
cursor = conn.cursor()
login_code = input("Enter the code: ")
cursor.execute("SELECT * FROM tst WHERE code = ?", login_code)
data = cursor.fetchall()
if not data:
print('> Not found')
self.log_in()
else:
cursor.execute("SELECT username FROM tst WHERE code = ?", login_code)
data = cursor.fetchall()
reducing_string = str(data)[1:-1]
last_cut = str(reducing_string)[1:-1]
print("")
print("Welcome", last_cut)
return login_code
def forgot_details(self):
cursor = conn.cursor()
login_username = input("> Username: ")
login_password = input("> Password: ")
cursor.execute("SELECT code FROM tst WHERE username = ? AND password = ?", login_username, login_password)
data = cursor.fetchall()
if not data:
self.forgot_details()
else:
reduction = str(data)[1:-1]
self.loading_bar()
print("> Your details are: ", str(reduction)[1:-1])
print("> To log in enter the code below: ")
self.log_in()
conn.commit()
class Logged:
def who(self):
cursor = conn.cursor()
cursor.execute("SELECT username FROM tst WHERE code = ?", #NOT SURE WHAT TO WRITE HERE)
data = cursor.fetchall()
print("Welcome user called: "data)
conn.commit()
def login_menu(self):
print("")
print("> Choose one of the following: ")
print("> 1: One \n"
"> 2: Two \n"
"> 3: Three \n"
"> 4: Four")
user_ask = input("> : ")
if user_ask == "1":
print("One")
elif user_ask == "2":
print("Two")
elif user_ask == "3":
print("Three")
elif user_ask == "4":
print("Four")
else:
self.login_menu()
First issue:
def log_in(self):
cursor = conn.cursor()
login_code = input("Enter the code: ")
This does not store the login_code variable to be retrieved later. login_code is only available during the execution of log_in(). To save it for later, you need to explicitly make login_code a member of some object (or make it an object in its own right in a higher scope). This might mean using self.login_code, or it might mean making login_code a member of some other object that is a member of the Database object.
If you want login_code to be a member of the Database class, you must explicitly refer to it as self.login_code. Python doesn't automatically include the object's member variables in the scope of methods like C++ (and Java?) do.
after this, the class Logged gets executed and when it runs I want to see what user is logged in from a method called who().
You could
Make login_code a global variable and use its value in the Logged.who() method. This is probably a bad idea.
Make login_code a member of the Database class and make the database instance a member of Logged so it can be fetched.
Make login_code a member of Logged and give the Database class a way to set it when executing the log_in method.
Make login_code a member of some other object that is passed as an argument to Database.log_in() and Logger.who() so that it can be accessed from both methods.

Query based on user input, return result, then run query with new user input

I am trying to query a database based upon user input, if the data exist then print the data, otherwise prompt entering new data. Upon query, the code only returns one time.
I've tried to use the while True: statement, it queries the data based upon the original input repeatedly.
I would like to query based on input, return a result, then reset query based on new user input. Can't seem to figure this one out. Any help would be appreciated.
user_input = input("Scan ID: ")
def read_from_db():
try:
c.execute("SELECT * FROM users WHERE barcode LIKE %s", ("%" + user_input + "%",))
result = c.fetchall()
if result is not None:
print ('Name:' , result[0][1], '| barcode: ' , result[0][3], ' | crew position: ' , result[0][4])
except:
print ("Register new user")
def main():
read_from_db()
if __name__ == '__main__':
try:
db = MySQLdb.connect("localhost","user","pw","database")
c= db.cursor()
except:
print ("not working...")
This did the trick -
while True:
user_input = input("Scan ID: ")
read_from_db = c.execute("SELECT * FROM users WHERE barcode LIKE %s", ("%" + user_input + "%",))
result = c.fetchall()
#print (result)
today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print (today)
if len(result) == 1:
print ('Name:' , result[0][1], '| barcode: ' , result[0][3], ' | crew position: ' , result[0][4])
c.execute("INSERT INTO Data (first_name,last_init,crew,time) VALUES (%s,%s,%s,%s)", (result[0][1],result[0][2][:1],result[0][4],today,))
db.commit()
else:
print ("Register new user")
fn = input("First Name: ")
ln = input("Last Name: ")
bc = input("Scan ID: ")
cp = input("IP or Student: ")
c.execute("INSERT INTO users (first_name,last_name,barcode,crew_position) VALUES (%s,%s,%s,%s)", (fn,ln,bc,cp,))
db.commit()
SELECT *
FROM users
WHERE barcode
LIKE CONCAT('%',user_input,'%');

Sqlite3 database Python conditional statement

import sqlite3
conn = sqlite3.connect('LeVinEmployee.db')
profile = input("Are you a user? y/n: ")
if profile == 'y':
login = input("Enter login name: ")
#passw = input("Enter password: ")
c = conn.cursor()
c.execute("SELECT * FROM Employee WHERE Email = '" + login + "'")
result = c.fetchone()
if result[0] == 1:
print(c.fetchall())
else:
print("not")
else:
print("You are not a user")
What I am trying to do here is pretty simple. I am trying to create user login function. If user type 'y', program will simply ask to put login email. If user type correct email from database, print that customer information. if wrong, print 'not'. I am not sure what is wrong with my code. Can someone help me please?
As I understand, email is an unique field. And your query could return one record or nothing (None). Try
result = c.fetchone()
if result: # result could be None or tuple (record)
print(result)
else:
print("not")
Also, such method of parameter pass is incorrect (insecure)
c.execute("SELECT * FROM Employee WHERE Email = '" + login + "'")
use
c.execute("SELECT * FROM Employee WHERE Email=?", login)
more info here.

TypeError: 'NoneType' object has no attribute '__getitem__' tkinter error

The issue I am having here is that whenever I try to input data into my Username entry box (self.KUEntry.get()) and run the input from that box within my query, it returns none and throws the error listed in the question.
The function is supposed to check the stored salt and hash of a registered user and compare it with the password that they are typing into the entry box.
def login_verification(self):
username = self.KUEntry.get()
print username
cursor1.execute = ("SELECT salt FROM User WHERE username = (%s)", username)
salty = cursor1.fetchone() [0]
print salty
cursor2.execute = ("SELECT PashHash FROM User WHERE username = %s", (username))
hashy = cursor2.fetchone() [0]
print hashy
test = hashlib.sha512(username + salty).hexdigest
print test
if test == hashy:
self.mainscreen
else:
print "incorrect password"
Putting my code like this fixes the traceback error, but it does not return what is expected. Instead of my cursor1.fetchone and cursor2.fetchone methods returning the result of the query they return "none".
def login_verification(self):
username = self.KUEntry.get()
print username
cursor1.execute = ("SELECT salt FROM User WHERE username = %s", str(username))
salty = str(cursor1.fetchone())
print salty
cursor2.execute = ("SELECT PashHash FROM User WHERE username = %s", str(username))
hashy = str(cursor2.fetchone())
print hashy
test = hashlib.sha512(username + str(salty)).hexdigest
print test
if test == hashy:
self.mainscreen
else:
print "incorrect password"

Categories