It shows no error and is able to run, but the data in the SQLite table doesn't update. However other update function similar to this work
def seller_edit():
while True:
sellername = str(input("Enter your username: "))
with sqlite3.connect(r"C:\Users\User\Desktop\HFSystem\Assginment\HFuserinfo.db") as connect:
cursor = connect.cursor()
check = "SELECT * FROM sellerinfo WHERE Username = ?"
cursor.execute(check,[sellername])
results = cursor.fetchall()
if results:
Phone = int(input("Enter New Phone No.: "))
Email = str(input("Enter New Email: "))
Address = str(input("Enter New Address: "))
updateseller ="""UPDATE sellerinfo SET Phone = ?, Email=?,Address=? WHERE Username=?"""
cursor.execute(updateseller,[sellername,Phone,Email,Address])
connect.commit()
print("Seller Info Edited!")
connect.close()
seller_info_menu()
break
else:
print("ProductID does not recognised")
option = input("Do you want to try again (y/n): ")
if option.lower() == "n":
seller_info_menu()
break
The order of the parameters inside the tuple of the 2nd argument of cursor.execute() must be the same as the order of the ? paceholders:
cursor.execute(updateseller, (Phone, Email, Address, sellername))
Related
So I am trying to create a login system kinda, normal python terminal. I made a register function but I am struggling with the login one. I am trying to compare my input to the username and password and when I get that done i will add the id's. But how can I do that, I tried everything.
When I run the code and enter the right details, it is telling me "Login failed, wrong username or password", which means that something is wrong with my if statement.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=""
)
mycursor = mydb.cursor(buffered=True)
def login():
mycursor.execute("USE logintest")
login_username = input("Please enter your username or email: ")
login_password = input("Please enter your password: ")
check_login = f"SELECT username FROM users WHERE username = '{login_username}'"
check_password = f"SELECT password FROM users WHERE password = '{login_password}'"
mycursor.execute(check_login)
username_result = mycursor.fetchall()
mycursor.execute(check_password)
password_result = mycursor.fetchall()
passwordr = password_result
usernamer = username_result
print(usernamer)
print(passwordr)
if login_password == passwordr and login_username == usernamer:
print("Logged in successfully")
else:
print("Login failed, wrong username or password")
def register():
mycursor.execute("USE logintest")
new_username = input("please pick a username: ")
new_email = input("please enter your email: ")
new_password = input("please pick a password: ")
insert_new_user = "INSERT INTO users (username, email, password) VALUES (%s, %s, %s)"
new_user = (new_username, new_email, new_password)
mycursor.execute(insert_new_user, new_user)
mydb.commit()
print("User successfully created! insert id:", mycursor.lastrowid)
def options():
print("1. login")
print("2. register")
options = input("please pick 1 or 2: ")
if "1" in options:
login()
elif "2" in options:
register()
else:
print("please only select 1 or 2")
options()
options()
Usually when you fetch data from a database in python, it returns a list of the data, and input in python is a string, so in other words, you are comparing a string with a list which will always be false.
you should create a function for verifying the login details. This is how to verify the login details, it should be inside the function:
try:
username = input("your username")
password = input("your password")
conn = (your connection code);
result = conn.execute("SELECT * FROM yourTable WHERE usernameColumnOfYourTable = ? AND passwordColumnOFyourTable = ?", (username, password))
print("connected to database")
if (len(result.fetchall()) > 0):
print("user found")
else:
print("user not found")
except Exception as err:
print("couldn't connect")
print("General error :: ", err)
Note: ? is the parameter marker for pyodbc module, if you're using mysql connector, replace the ? sign with %s
But if you're using a hashed (salted) password, the format will be a bit different.
Applying this logic to your codes:
def login():
connection = (establish your database connection here)
login_username = input("Please enter your username or email: ")
login_password = input("Please enter your password: ")
result = connection.execute("SELECT username FROM users WHERE username = ? AND password = ?",(login_username, login_password) )"
if (len(result.fetchall()) > 0):
print("Logged in successfully")
else:
print("Login failed, wrong username or password")
I'm new to Python and SQLite3. I've created a database and am attempting to create an add function from user input. The addition to the DB is successful and fully callable through the menu until you exit. When you use the exit method on the menu theres an error and then the data isnt saved to the DB.
import sqlite3
conn = sqlite3.connect("Adventure_Time.db")
c = conn.cursor()
c.execute ("""CREATE TABLE IF NOT EXISTs characters(
first_name text,
last_name text,
email_address text,
phone_number int,
street_address text,
city_name text,
state_name text,
zipcode_number int)
""")
conn.commit()
def display_menu():
print("Welcome to the Adventure Time Database")
print()
print()
print("list - List all of the Records")
print("names - Show First and Last Names")
print("show - All Cities ")
print("add- Add a Character to the Database")
print("exit - Exit program")
print()
def add_charcter():
c = conn.cursor()
try:
first_name = input("First Name: ")
last_name = input("Last Name: ")
email_address = input("Email Address: ")
phone_number = int (input("Telephone Number: "))
street_address = input("Street Address: ")
city_name = input("City: ")
state_name = input("State: ")
zipcode_number = int(input("Zipcode"))
sql = """INSERT INTO characters(
first_name,
last_name,
email_address,
phone_number,
street_address,
city_name,
state_name,
zipcode_number)
VALUES (?,?,?,?,?,?,?,? )
"""
c.execute(sql, (first_name, last_name, email_address, phone_number, street_address,city_name, state_name,zipcode_number))
c.committ()
c.close
print("Record Submitted to Database")
finally:
main()
def main():
display_menu()
while True:
command = input("Command: ")
if command == "list":
list_characters()
elif command == "names":
names_characters()
elif command == "show":
show_contact()
elif command =="add":
add_charcter()
elif command == "exit":
break
else:
print("Not a valid command. Please try again.\n")
conn.close()
print("See you in the Nightosphere!")
if __name__ == "__main__":
main()
c = conn.cursor()
c is cursor object so you can not call commit on it.
you need to call conn.commit()
The aim of this code is to achieve the following:
-Enter username
-Check if exists on DB
-If not create new user
-Add currency & balance to new user row
The issue is with my insert statement. I'm not sure how to use the WHERE condition while inserting data using defined variables. Help would be welcomed!
Error Message: TypeError: function takes at most 2 arguments (4 given)
def add_user():strong text
print("enter new username")
UserLogin = str(input())
c.execute("SELECT username FROM FinanceDBTable")
enter code here
for row in c.fetchall():
print()
#Convers tuple to string without spaces
UserNameDB = ''.join(row)
if UserNameDB == UserLogin:
print('This username already exisits. please try again')
add_user()
else:
print("Please enter your balanace\n")
userbalance = input()
print("Please enter currency\n")
userCurrency = input()
c.execute("INSERT INTO FinanceDBTable (balance, currency) VALUES (?,?)",
(userbalance, userCurrency), "WHERE (username) VALUES (?)", (UserLogin))
conn.commit()
One way would be to do this, also does not use recursion which is seen as unpythonic and also will eventually throw errors. Plus made it a bit more pythonic.
I'm not sure if you can use WHERE in INSERT statements, you can in UPDATE maybe that where you're getting that idea from, but by also giving the username value with the other will work for what you are trying to achieve i think.
def add_user():
while True:
username = input("Username: ")
c.execute("SELECT username FROM FinanceDBTable WHERE username = ?", (username,))
results = c.fetchall()
if len(results) < 1:
# Add user as there is not user with that username.
user_balance = int(input("Please enter your balance: "))
user_currency = input("Please enter currency: ")
c.execute("INSERT INTO FinanceDBTable(username, balance, currency) VALUES (?,?,?)", (username, user_balance, user_currency))
conn.commit()
break
else:
# User already exists
print('This username already exists, please try again.')
I'm trying to enter details into an SQL database through Python. I have already created the database with fields customerID, firstname, surname, town and telephone.
When running this function, I get the error 'str' object is not callablefor the line where I am trying to INSERT the values of the variables.
import sqlite3
#function used to add a new customer, once confirmed save the customer in a
#customer list
def add_customer():
#open up the clients database
new_db = sqlite3.connect('clients.db')
#create a new cursor object to be able to use the database
c = clients_db.cursor()
print("Add customer")
firstname = ""
while len(firstname) == 0:
firstname = input("Enter the customer's first name: ")
surname = ""
while len(surname) == 0:
surname = input("Enter the customer's surname: ")
town = ""
while len(town) == 0:
town=input("Enter the customer's town: ")
telephone = '1'
while len(telephone) != 11:
while telephone[0] != '0':
telephone = input("Please enter the customer's telephone number: ")
if telephone[0] != '0':
print ("telephone numbers must begin with zero")
elif len(telephone) != 11:
print("must have 11 numbers")
#check that data has been entered
print(firstname,surname,town,telephone)
#insert data into the customer table
c.execute('INSERT INTO Customer VALUES (NULL, ?,?,?,?,)'(firstname, surname, town, telephone))
print("Customer added successfully ...")
clients_db.commit()
clients_db.close()
if choice ==1:
another = input("Would you like to add another? yes [y] or no [n] --> ")
if another=='y':
add_customer()
else:
main_menu()
You forgot a comma between the SQL statement string and the parameters:
c.execute('INSERT INTO Customer VALUES (NULL, ?,?,?,?,)'(firstname, surname, town, telephone))
# ^
so you effectively do this: "some string"(arg1, arg2, ...), trying to treat the string as a function.
Simply insert a comma there:
c.execute(
'INSERT INTO Customer VALUES (NULL, ?,?,?,?,)',
(firstname, surname, town, telephone))
i am trying to edit a record from my database by letting the user select what they want to edit within that record.
i get the following error
UnboundLocalError: local variable 'Type' referenced before assignment
my code is as following:
import sqlite3
def update_data(values):
with sqlite3.connect("mrsimms.db")as db:
cursor = db.cursor()
sql = "Update Stock set Type=?,RetailPrice=?, NumberInStock=? where Name=?"
cursor.execute(sql,values)
db.commit()
def update():
Update = "y"
while Update == "y":
Name = input("Please enter the name of the product you wish to update: ")
Type_change=input('would you like to edit the type?(y/n) ')
if Type_change == 'y':
Type=input("Please enter the updated type: ")
RetailPrice_change=input('would you like to edit the retail price?(y/n) ')
if RetailPrice_change=='y':
RetailPrice = input("Please enter the updated retail price: ")
NumberInStock_change=input('would you like to edit the number in stock?(y/n) ')
if NumberInStock_change=='y':
NumberInStock = input("Please enter the updated number in stock: ")
data = (Type,RetailPrice,NumberInStock)
update_data(data)
Update = input("Do you wish to update another lesson? (y/n) ")
print()
update()
thank you :)
You have this code.
if Type_change == 'y':
Type=input("Please enter the updated type: ")
There is no else and Type is not assigned to later.
So here
data = (Type,RetailPrice,NumberInStock)
Type dos not exist if the ifcondition was not true.
Add an else clause or initialize Type outside the if.