I'm doing a code where the program ask for personal informations of someone, then he reads those infomations and send to the database. So I have the option to register and to consult. I don't know if the program is with more problems because I need to fix it first.
When I try to register the person It's give me the error "Is not possible to register." and I can't find why.
import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
def criardb():
c.execute('CREATE TABLE IF NOT EXISTS pessoas(id INTEGER PRIMARY KEY
AUTOINCREMENT,nome VARCHAR, idade INT, tel VARCHAR, pais VARCHAR)')
conn.commit()
def insertdata(nome,idade,tel,pais):
c.execute = ('INSERT INTO pessoas VALUES (?,?,?,?)',
(nome,idade,tel,pais))
conn.commit()
def consultdata():
sql = c.execute('SELECT * FROM pessoas')
for row in sql:
print("Nome: {}".format(row[0]))
def consultdataind(esc):
sql = c.execute('SELECT * FROM pessoas WHERE id = ?')
for row in sql(sql,(esc)):
print("Nome: {} Idade: {} Telefone: {} País:
{}".format(row[0],int(row[1]),row[2],row[3]))
try:
print("Creating database...")
criardb()
except:
print("ERRO: It was not possible to create the database.")
else:
print("Database successfully created.")
while True:
print("Welcome to the register system, choose a option:")
op = int(input("| 1 - Register | 2 - Consult | 3 - Exit | "))
if op == 1:
n = input("Nome: ")
i = int(input("Idade: "))
t = input("Telefone: ")
p = input("País: ")
try:
insertdata(n,i,t,p)
except:
print("ERRO: It's not possible to register")
else:
print("Successfully registered.")
elif op == 2:
print("List of registered users:")
try:
consultdata()
except:
print("It was not possible to load the list.")
print("Write the person ID to individual consult.")
esc = int(input(">> "))
consultdataind(esc)
elif op == 3:
break
else:
print("Invalid command.")
I need to send all the information to the database and return the consult, first it will show all the registered person then the user can write the respective ID of someone in the list and it will show all the details about this person
Replace your insertdata with this and everything should work fine.
def insertdata(nome,idade,tel,pais):
c.execute('INSERT INTO pessoas (nome,idade,tel,pais) VALUES (?,?,?,?)', [nome,idade,tel,pais])
conn.commit()
You need to call the execute method of the cursor here.
And on the side note, never use except directly without specifying an exception. It hides the simplest of error messages which will make your code very hard to debug. As of now it was AttributeError that was causing this problem as you were trying to assign value to Cursor which is ReadOnly
Related
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")
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.
I'm relatively new to Python and currently working on a 2nd tutorial, specifically working with SQLite.
In my attached code (specifically the function Update), I have 3 while loops and several breaks within just this simple function. I am thinking that this is not good practice and I am looking for advice to make it less vulnerable to crashing and/or more compact.
What are the side effects of having too many break statements?
def updateData():
global cursor
sql = 'SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name'
cursor.execute(sql)
rows = cursor.fetchall()
print("These are the existing tables in the system:")
tableList = []
for row in rows:
print(row[0])
tableList.append(row[0])
while True:
table = input("Enter table to update: ")
if table in tableList:
while True:
phoneLIST = searchDB()
if len(phoneLIST) == 0:
option = tryMessage()
if not option:
break
else:
numID = int(input("Enter the ID number you want updated: "))
sql = 'PRAGMA table_info(%s)' % table
cursor.execute(sql)
rows = cursor.fetchall()
print("These are the existing columns in %s table:" % table)
colList = []
for row in rows:
print(row[1])
colList.append(row[1])
while True:
column = input("Enter the column name of ID: %d you want updated: " % numID)
column = column.upper()
if column in colList:
if column == 'BOD' or column == 'PID':
print("You can't change Birth of Date OR PID")
option = tryMessage()
if not option:
break
else:
if column == 'PHONE':
newEntry = checkPhone()
elif column == 'POSTAL':
newEntry = checkPostal()
else:
newEntry = input("Enter new information for column %s: " % column)
sql = 'UPDATE %s SET %s = "%s" WHERE PID = %d' % (table, column, newEntry, numID)
cursor.execute(sql)
displayOneEntry(numID)
commitMessage()
break
else:
print("Column not in the table")
break
break
else:
print("Table not in the database")
option = tryMessage()
if not option:
break
There's nothing wrong with while True: loops; they're the natural way of doing something over and over until an error happens or the user decides to quit.
In my opinion this function is a bit clumsy, because it's working at many different levels of detail. It might be better to reorganize it into separate functions for tables, column IDs, and values, so that each function is concerned just with its own stuff and doesn't worry about higher- or lower-level details.
I have refactored as follows, eliminating the nested while True:
Thanks again #JG!
{other functions ...}
def getTable():
global cursor
sql = 'SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name'
cursor.execute(sql)
rows = cursor.fetchall()
tableList = []
print("These are the available tables: ")
for row in rows:
print(row)
tableList.append(row[0])
while True:
tableName = input("Enter table to update: ")
if tableName in tableList:
return tableName
break
else:
print("Table not in the database")
# provide option to re-enter information
option = tryMessage()
if not option:
break
def getColumn(tableName, numID):
global cursor
sql = 'PRAGMA table_info(%s)' % tableName
cursor.execute(sql)
rows = cursor.fetchall()
print("These are the existing columns in %s table:" % tableName)
colList = []
for row in rows:
print(row[1])
colList.append(row[1])
while True:
colName = input("Enter the column name of ID: %d you want updated: " % numID)
colName = colName.upper()
if colName in colList:
return colName
else:
print("Column not in the table")
# provide option to re-enter information
option = tryMessage()
if not option:
break
def getID(idList):
while True:
try:
numID = int(input("Enter the ID number you want updated: "))
except ValueError:
print('Enter valid number')
continue
if numID in idList:
return numID
else:
print("Wrong ID")
# admin use only
def updateData():
global tempPassword
passWord = input("Enter password: ")
if passWord == tempPassword:
global cursor
# Displays valid tables
tableName = getTable()
idName = getIDName(tableName)
while True:
idList = searchDB()
# provide option to re-enter information
if len(idList) == 0:
option = tryMessage()
if not option:
break
else:
numID = getID(idList)
colName = getColumn(tableName, numID)
if colName == 'BOD' or colName == idName or colName == 'STATUS':
print("You can't change this field")
# provides option to re-enter information
option = tryMessage()
if not option:
break
else:
if colName == 'PHONE':
# checks format for phone input
newEntry = checkPhone()
elif colName == 'POSTAL':
# checks format for postal code input
newEntry = checkPostal()
elif colName == 'POSITION_ID':
# checks to ensure ID is valid
newEntry = checkPositionID()
else:
newEntry = input("Enter new information for column %s: " % colName)
sql = 'UPDATE %s SET %s = "%s" WHERE %s = %d' % (tableName, colName, newEntry, idName, numID)
cursor.execute(sql)
# display the updated entry for confirmation
displayOneEntry(idName, numID)
# provide option to commit changes
commitMessage(idName)
break
else:
print("Access requires correct password")
{menu ...}
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.
I am writing a python function that takes an input from a user, searches for it in a database and then checks the input against the return result and if correct proceeds with the program and if incorrect asks the user to re-enter. This doesn't work however. When a user enters something it just says it is incorrect as per my program. Here is the code:
def TakeOutItem():
Serial = input("Please enter the serial number of the music you are taking out: ")
SerialN = int(Serial,)
with sqlite3.connect("school.db") as db:
cursor = db.cursor()
cursor.execute("SELECT SerialNo FROM Music WHERE SerialNo=?",(SerialN,))
data = cursor.fetchone()[0]
print(">>",SerialN, data,">>")
print(type(SerialN),type(data)).show
print(int(SerialN) == int(data))
if SerialN == int(data):
DateOut = date.today()
DateIn = date.today() + timedelta(days=30)
cursor.execute('SELECT Name FROM Music WHERE SerialNo=?', Serial)
NameofMusic = cursor.fetchone()
cursor.execute('SELECT StudentID FROM Student WHERE username=?', student_login(username))
StudentID = cursor.fetchone()
cursor.execute('INSERT INTO MusicLoan VALUES (?,?,?,?,?)', DateOut, DateIn, Music, NameofMusic, StudentID)
print("Item taken out successfully")
student_menu()
else:
print("Incorrect Serial Number please try again")
TakeOutItem()
and this is the error screen
What would you like to do?
1. Take out item
2. Return item
3. Exit
Please select an option number: 1
Please enter the serial number of the music you are taking out: 1
>> 1 1 >>
<class 'int'> <class 'int'>
Please select a valid option
The it takes me back to he previous menu
How can I fix this error??
cursor.fetchone() will always return a tuple.So use
data = cursor.fetchone()[0]
or
if SerialN == data[0]:
Inside your if condition also, please rewrite it to NameofMusic[0] and StudentID[0] in your INSERT query