def update_employee_table(self,ids,username, password, first_name, last_name,age, phone_number, department, city, address):
self.connect()
print(self)
self.c.execute("UPDATE employee SET (username,password,first_name,last_name,age,phone_number,department,city,address) VALUES (?,?,?,?,?,?,?,?,?) WHERE id = ?",(username, password, first_name, last_name,age, phone_number, department, city, address),(ids))
self.commit()
i am trying to update a table by the id and insert the values that i have passed to the function , the syntax of the update confuses me a little and i get this error : TypeError: function takes at most 2 arguments (3 given)
You must include the variable ids inside the tuple that you pass as the 2nd argument of execute() and not as a 3d argument.
Also, the UPDATE statement is syntactically wrong as it is written with VALUES.
Write it like this:
sql = """
UPDATE employee
SET (username,password,first_name,last_name,age,phone_number,department,city,address) = (?,?,?,?,?,?,?,?,?)
WHERE id = ?
"""
self.c.execute(sql, (username, password, first_name, last_name, age, phone_number, department, city, address, ids))
Related
How can I put a python variable just after the SELECT. The idea is to create a python function with three arguments where you can choose what you what (here, it's the age) from whom (here, it's Mike and James)
conn = sqlite3.connect('test.s3db')
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS people''')
cur.execute('''CREATE TABLE IF NOT EXISTS people
(id INTEGER,
name TEXT,
surname TEXT,
age INTEGER,
alone INTEGER DEFAULT 0);''')
def add_people(id, name, surname, age, alone=0):
cur.executemany('INSERT INTO people (id, name, surname, age, alone) VALUES (?,?,?,?,?)', [(id, name, surname, age, alone)])
conn.commit()
add_people(1, 'SMITH','James',45)
add_people(2,'JOHNSON','Mike',75)
cur.execute('''SELECT (?) FROM people WHERE surname = (?) OR surname = (?)''', ('age','Mike', 'James'))
print(cur.fetchall())
My code return:
[('age',), ('age',)]
instead of :
[(75,), (45,)]
EDIT : I want that what is selected is a variable and not directly written in the query. My goal is to make a function like this one :
def query(what, who_1, who_2):
cur.executemany('''SELECT (?) FROM people WHERE surname = (?) OR surname = (?)''', (what, who_1, who_2))
return cur.fetchall()
Thank you in advance for your answers !
This takes the data you need as argument of select_data_of
import sqlite3
def add_people(id, name, surname, age, alone=0):
cur.executemany('INSERT INTO people (id, name, surname, age, alone) VALUES (?,?,?,?,?)', [(id, name, surname, age, alone)])
conn.commit()
def select_data_of(names, data="age"):
select = []
for name in names:
cur.execute(f'''SELECT [{data}] FROM people WHERE surname = (?)''', (name, ))
select.append(cur.fetchall()[0])
return select
with sqlite3.connect('test.s3db') as conn:
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS people''')
cur.execute('''CREATE TABLE IF NOT EXISTS people
(id INTEGER,
name TEXT,
surname TEXT,
age INTEGER,
alone INTEGER DEFAULT 0);''')
add_people(2,'JOHNSON','Mike',75)
add_people(1, 'SMITH','James',45)
data = select_data_of(("Mike", "James"), data="age")
print(data)
OUT:
[(75,), (45,)]
I think your select query is wrong because of the 'ages' parameter, this new query will work.
Try
cur.execute("SELECT [age] FROM people WHERE surname = 'Mike' OR surname = 'James")
Still new to API's so please excuse any novice mistakes
This is where I receive the input from another port and then it gets sent to PUT method
#app.route('/PUT', methods=['POST'])
def PUT_link():
first_name = request.form['fname']
last_name = request.form['lname']
number = request.form['number']
Methods.PUT(first_name, last_name, number)
return 'success'
This is the method that should update the number but it doesn't.
#classmethod
def PUT(cls, first_name, last_name, number):
connection = sqlite3.connect('data.db')
cur = connection.cursor()
query = "UPDATE contacts SET number=? WHERE firstname=? AND lastname=?"
cur.execute(query, (first_name, last_name, number))
connection.commit()
connection.close()
return 'Contact number updated'
I'm trying to create a method to update rows in a sqlite database. I would like to use Python's sqlite3 module to achieve this. My function looks something like this:
import sqlite3
def update(first_name=None, last_name=None, email_address=None, password=None):
if not email_address:
raise TypeError("Required keyword argument email_address is missing!")
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute(
"""
UPDATE users
SET first_name = ?, last_name = ?, password = ?
WHERE email_address = ?
"""
)
conn.commit()
conn.close()
return
'email_address' is the unique identifier in this case and is therefore required. The other arguments should be optional.
At this moment, the fields in the database will be overwritten with "NULL" if the user doesn't pass in all arguments, because the keyword arguments default to 'None'. Obviously this implementation is not useful when the user only wants to update only one or a few fields. Especially so if the database includes more fields (this is just an example).
A solution would be to change the SET part of the query depending on whether the keyword argument is 'True' or 'False'. For example, if only 'first_name', 'last_name' and 'email_address' are passed as keyword arguments:
UPDATE users
SET first_name = ?,
last_name = ?
WHERE email_address = ?
And if only 'first name' and 'email_address' is are passed as keyword arguments:
UPDATE users
SET first_name = ?
WHERE email_address = ?
How can I handle these optional arguments in the query that's passed into the execute() method? sqlite3 seems to be very inflexible because it's string-based. I have considered building a string constructor, but this seems to complex. I hope there's a more elegant way to solve this.
Ran into a similar problem myself. Here is what I came up with:
import sqlite3
def update(email, params):
fields_to_set = []
field_values = []
# loop thru the params passed
for key in params:
# build up the SET statement using the param keys
fields_to_set.append(key + "=?")
# save the values to be used with the SET statement
field_values.append(params[key])
# join the SET statement together
set_statement = ", ".join(fields_to_set)
field_values.append(email)
cmd = "UPDATE users SET "+set_statement+" WHERE email_address=?"
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute(cmd, field_values)
conn.commit()
conn.close()
# now you can pass just the parameters you want to update
update("john.doe#test.com", {"first_name": "John", "last_name": "Doe"})
update("john.doe#test.com", {"password": "john doe's password"})
NOTE: this requires that your params keys are identical to your field names
Code:
def execute():
cursor.execute('''
INSERT INTO Testb(First_name, Last_name, Tel_number, Address)
VALUES(?,?,?,?)
''')
conn.commit()
Can we add a different type of value to the VALUES? My intent is to insert an output to the value which is outside the function. As an example, if I get the output x=456 in which x is the variable, how can I insert it to the Tele_number to the corresponding value?
You can use str.format() to allow multiple substitutions and value formatting.
For your case:
def execute():
first_name = 'Twilight'
last_name = 'Moon'
telephone = '4569876521'
address = 'Somewhere, '
cursor.execute("INSERT INTO Testb(First_name, Last_name, Tel_number, Address)
VALUES({},{},{},{})".format(first_name, last_name, telephone, address))
conn.commit()
Refer to this link to learn more about string formatting in python.
I have been working on this function in python. I intend for it to iterate over a list of phone numbers, checking with a database to see whether the number has been used yet or not. If it has been used, it should remove the phone number from the list and choose another and check the new one until an unused one has been found and return the unused one. If it has not been used, it should simply just return the number. However, after one run, it picks a number, checks it, runs, and then enters it into the database. The next run deletes the previously used number, and picks another that hasn't been used. It continues to run and enters this number into the database. The third run does not delete the previously used number from the list, but it still picks a new one regardless. Although this still works, when the numbers run out, since there are no others to pick, it continues using the last number in the list for every following run of the script. Sorry if the code is a bit sloppy right now, I am in a bit of a rush and this is only a script I have been messing around with. I hope this is clear, and not too confusing. If I need to clear any confusion, I will be glad too.
Edit: Sorry, I forgot to mention that these phone numbers are constantly grabbed from a website by another script. These set of numbers listed below is just a dummy set for testing. So in the end, I am needing to see if these recently grabbed numbers have been used by checking with the database tables.
import random
import names
##############################Information Variables##################################
emailAddress = "Fakeemail#mail.com"
titleValues = [0,1] #0 is 'Mr.', 1 is 'Mrs.'
country = 'Schwifty'
title = random.choice(titleValues)
#Generate a random name based on gender
if title == 1:
firstName = names.get_first_name(gender= 'female')
else:
firstName = names.get_first_name(gender= 'male')
lastName = names.get_last_name()
fullName = firstName + ' ' + lastName
print(fullName)
phoneNumber = '111-222-3333'
#########################################################
import sqlite3
import time
import datetime
conn = sqlite3.connect('accounts.db')
c = conn.cursor()
def createTable():
c.execute('CREATE TABLE IF NOT EXISTS accounts(Email TEXT, Name TEXT, Title TEXT, PhoneNumber TEXT, Country TEXT, DateStamp TEXT)')
def dynamic_data_entry(email, name, title, phone, country):
unix = time.time()
date = str(datetime.datetime.fromtimestamp (unix).strftime('%Y-%m-%d %H:%M:%S'))
c.execute('INSERT INTO accounts (Email, Name, Title, PhoneNumber, Country, DateStamp) VALUES (?, ?, ?, ?, ?, ?)', (email, name, title, phone, country, date))
conn.commit()
createTable()
#################################TEST NUMBER CHECK###########################
phoneNumbers = ['111-222-3333', '444-555-6666', '777-888-9999', '123-456-7890', '321-321-321']
def checkNumber(a):
c.execute("SELECT * FROM accounts WHERE PhoneNumber = ?", (a,))
row = c.fetchall()
if row:
print("Phone number has already been used, choosing another and deleting current from list.")
phoneNumbers.remove(a)
a = random.choice(phoneNumbers)
checkNumber(a)
elif row == False:
print("Number is fresh and new, using " + a)
return a
elif row == None:
print('No new phone numbers to use, exiting... ')
exit()
# for num in phoneNumbers:
# checkNumber(num)
# print(num)
checkNumber(phoneNumber)
print(phoneNumbers)
print('working')
##########################################
# INSERT DATA TO DB #
##########################################
#Insert information to database in this order: email, name, title, phone, country
dynamic_data_entry(emailAddress, fullName, title, phoneNumber, country)
conn.commit()
c.close()
conn.close()
Don’t do this. Populate a table with your phone numbers and update each phone number record with a field like ‘used’ once used.
Always keep state and data modeling in the database where possible. It is made for it.
Update in response to OP:
Create a separate table for phone numbers and replace your number field in the accounts table with a foreign key id to the primary key of the phone number table. This is called maintaining an object model or data model, so that if you want to query accounts, you have the data you need via foreign key, and if you just want phone numbers you can query the phone numbers table directly.
This way your phone number ‘objects’ can have their own attributes like ‘already called’ or ‘on do not call list’ without muddying up your accounts ‘object’.
If you want to insert a new account, you should first insert your new phone number 'object' into the phone number table and return the id, and then use that in your account insert.