How do i write a query if the multiple form field data are being searched in mysql database.
The form fields are as follow
FirstName:
LastName:
Age:
Gender:
Now we can enter data in any multiple field and make a search
the code i have tried works for single field. Unable to create for multiple conditions
sql = "select * from PERSON where F_Name = %s or L_Name = %s or Age = %s and Gender = %s"
self.cursor.execute(sql,(self.fname, self.lname, self.age, self.gender))
If field FirstName and Gender are filled
If field Lastname, Gender, age are filled
If field FirsName, Age are filled
If field Gender and lastname are filled
like all possible conditions
This is not python or any language specific. This is about query syntax.
Try this
sql = "select * from PERSON where (F_Name = '%s' or L_Name = '%s' or Age = '%s') and Gender = '%s';"
self.cursor.execute(sql % (self.fname, self.lname, self.age, self.gender))
Refer this http://www.tuxradar.com/practicalphp/9/3/13
Related
I am writing a function in python that will update some of the columns in a row of a mysql table. What the function does is it asks for id, then the function shows the record before the update, then asks for user input new values in every column. Within the function, I mentioned "to re enter values that do not need changes". I learned that it is easier to just press enter for fields that do not need updates. But in my current function, when I press enter for fields that do not need an update, it deletes the value.
def update_details(id):
print('Before updating the account details:')
before_update = 'SELECT * FROM cdw_sapp_customer WHERE id = %s'
mycursor.execute(before_update, (id,))
record = mycursor.fetchone()
print(record)
print('\n')
print('Enter the new account details (re-enter detail if no change is necessary):')
first_name = input('Enter the new first name: ').title()
middle_name = input('Enter the new middle name: ').lower()
last_name = input('Enter the new last name: ').title()
street_add_apt = input('Enter the new street address,apartment number(if any): ')
country = input('Enter the new country: ').title()
# I had to put this zip required, because I am having issue when I just pressed enter
zip = int(input('REQUIRED: old or new: Please enter the new zip code: '))
phone = input('Enter the new phone number in xxx-xxxx: ')
email = input('Enter the new email: ')
print('\n')
update = 'UPDATE customer SET FIRST_NAME = %s, MIDDLE_NAME = %s, LAST_NAME = %s, FULL_STREET_ADDRESS = %s, ZIP = %s, PHONE = %s, EMAIL = %s WHERE id = %s'
mycursor.execute(update, (first_name, middle_name, last_name, street_add_apt, country, zip, phone, email, id))
mydb.commit()
# show the new record
after_update = 'SELECT * FROM cdw_sapp_customer WHERE id = %s'
mycursor.execute(after_update, (ssn,))
# record = mycursor.fetchone()
# print(record)
print('\n')
# update the last_updated field in the cdw_sapp_customer table with the date and time of the new details
update_last_updated = 'UPDATE cdw_sapp_customer SET LAST_UPDATED = CURRENT_TIMESTAMP WHERE id = %s'
mycursor.execute(update_last_updated, (id,))
mydb.commit()
print('\n')
print('Updated account details:')
after_update = 'SELECT * FROM customer WHERE id = %s'
mycursor.execute(after_update, (id,))
record = mycursor.fetchone()
print(record)
print('\n')
Initially, the function above, users have to put entries in every question. What I would like to happen is that if the information is the same of any field, they just press enter and when the function returns the line of new record, all other information that does not need to be changed will be the same. From the above function, when I just press enter, it deletes the entry for the field.
I am trying to update records from my database named Template, Table clients. I get my updated information from a Tkinter Treeview. I am updating any field except user_id which is my primary key. I get a syntax error on cur.execute(sql_command). cur is define as my cursor.
# Function to Edit Record
def edit_client():
# Update the Database
print(user_id_box.get())
sql_command = ("UPDATE clients SET \
f_name = f_name_box.get(),\
l_name = l_name_box.get(),\
email = email_box.get(),\
phone = phone_box.get(),\
price = price_box.get(),\
address = address_box.get(),\
city = city_box.get(),\
state = state_box.get(),\
country = country_box.get(),\
zipcode = zipcode_box.get() WHERE user_id = user_id_box.get()")
# Execute the SQL command
cur.execute(sql_command)
# Commit the changes to the database
mydb.commit()
# Clear the old entry
clear_record()
# Refresh the Data Frame
query_database()
Note that f_name.get() inside a string like "f_name = f_name.get()" will not work.
For your case, you can use placeholder (%s for MySQL) in SQL statement:
sql_command = f"""UPDATE clients
SET f_name = %s, l_name = %s,
email = %s, phone = %s,
price = %s, address = %s,
city = %s, state = %s,
country = %s, zipcode = %s
WHERE user_id = %s"""
cur.execute(sql_command, (f_name_box.get(), l_name_box.get(),
email_box.get(), phone_box.get(),
price_box.get(), address_box.get(),
city_box.get(), state_box.get(),
country_box.get(), zipcode_box.get(),
user_id_box.get()))
The simplest solution would be using f-string and braces to properly put values inside string. Here I also used docstrings, so you don't need backslashes.
def edit_client():
print(user_id_box.get())
sql_command = f"""UPDATE clients SET
f_name = {f_name_box.get()},
l_name = {l_name_box.get()},
email = {email_box.get()},
phone = {phone_box.get()},
price = {price_box.get()},
address = {address_box.get()},
city = {city_box.get()},
state = {state_box.get()},
country = {country_box.get()},
zipcode = {zipcode_box.get()} WHERE user_id = {user_id_box.get()}"""
cur.execute(sql_command)
mydb.commit()
clear_record()
query_database()
HOWEVER
I do strongly recommend you to sanitise your inputs and pass them as arguments to executor, as SQL injections are still a thing, even if you don't care about security, you can still simply break query, by having broken inputs.
I do not know which library you utilise in order to communicate with DB, but it's documentation should cover it, if it is not from early 1970, created by some student.
I'm trying to create a contact book as a personal project. In the 'find_contact()' function, when I use the 'emaiL' variable to perform a query, it error message says that the data (I pre-recorded in the table) doesn't exist. But when I changed the variable to be used to query to 'phoneNum' (which is a number in text form) the query worked. How do I go about this please?
import sqlite3
conn = sqlite3.connect('contactBook.db')
cur = conn.cursor()
records = cur.fetchall()
#create table
cur.execute("""CREATE TABLE IF NOT EXISTS contacts (
first_name TEXT NOT NULL,
last_name TEXT,
phone_number TEXT NOT NULL PRIMARY KEY,
email,
address TEXT,
UNIQUE(phone_number, email)
)""")
#conn.close()
def save_contact():
save_contact.firstName = input("First name of contact: ")
lastName = input("Last name of contact: ")
phoneNumber = input("Phone number of contact: ")
email_ = input("Email of contact: ")
address_ = input("Address of contact: ")
cur.execute("INSERT OR IGNORE INTO contacts (first_name, last_name,phone_number,
email,address) VALUES (?, ?, ?, ?, ?)",
(save_contact.firstName, lastName, phoneNumber, email_, address_))
conn.commit()
def find_contact():
emaiL = input('Enter email: ')
query = f'''SELECT * FROM contacts WHERE email = {emaiL}'''
lua = f'''SELECT first_name, phone_number FROM contacts WHERE email = {emaiL}'''
#cur.execute("SELECT * FROM contacts (email) VALUES (?)", (email,))
cur.execute(query)
#conn.commit()
print(cur.execute(lua))
req = input("Hello, would you like to save or search for a contact: ")
if str.lower(req) == 'save':
save_contact()
x = save_contact.firstName
print("You have successfully saved " + x + "'s details")
elif str.lower(req) == 'search':
find_contact()
The test run was:
Hello, would you like to save, search or update for a contact:
search
Enter email: mine
The traceback:
Traceback (most recent call last):
File "c:\Users\GLORIA\Desktop\MINE\db.py", line 60, in <module>
find_contact()
File "c:\Users\GLORIA\Desktop\MINE\db.py", line 33, in
find_contact
cur.execute(query)
sqlite3.OperationalError: no such column: mine
query = f'''SELECT * FROM contacts WHERE email = {emaiL}'''
If the value of the variable emaiL is the string 'mine', this creates the SQL statement
SELECT * FROM contacts WHERE email = mine
but in this statement, mine would be interpreted by SQLite as a column name. If you want it to be interpreted as a string, quotes would need to be added:
SELECT * FROM contacts WHERE email = "mine"
However, don't try to adjust the string formatting line, query = f'''...''' to add the quotes, instead use a parameterized statement with ? as a placeholder, like you did for the other SQL statements in your code.
query = 'SELECT * FROM contacts WHERE email = ?'
cur.execute(query, (emaiL,))
See How to use variables in SQL statement in Python? for reasons to do so.
In the query query = f'''SELECT * FROM contacts WHERE last_name = {emaiL}''' is it not supposed to be f'''SELECT * FROM contacts WHERE email = {emaiL}'''?
It's probably because your {emaiL} doesn't have quotes for the email in the query, like this:
f'''SELECT * FROM contacts WHERE email = '{emaiL}' '''
If you print out your current query variable, you'll get SELECT * FROM contacts WHERE email = mine, which isn't valid. You want to get the string SELECT * FROM contacts WHERE email = 'mine'.
I have created a table to store information and data for each user in a simple social media website. I have the column "friends" and I want this column to have multiple values seperated by a comma. for example, "John, Maria, Batman etc...". Shortly, each time the user clicks at the Follow Button, the name of the another person is being added to the column "friends".
with sqlite3.connect('memory.db') as conn:
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE users (user_id char(50), name char(50), email char(50), password char(30), "
"university char(50), birthday char(50), age char(10), hometown char(50), photo, status char(50), friends char(1000));")
name = session['name'] #the name of the user
name_search = session['name_search'] #the name of the person who we want to follow
if name != name_search:
cursor.execute('''UPDATE users SET friends=? WHERE name=?''', (name_search, name))
conn.commit()
I've used the method UPDATE but it updates the column only with the one value...
I have a form which 4 input fields, when clicking the submit button, I'm fetching results from the database based on those 4 inputs. I'm not forcing the user to enter any input, so I could get all blank inputs or part of them empty. The more inputs the user fills, the results from the database will be more precise.
My problem is how to build the where part of the query dynamically using only the place holders which are populated. here is my query. This way if one of the inputs are blank, the query will not fetch anything while my intention is the opposite: if the input is blank, do not take into account while querying the database.
cursor.execute('''
SELECT name, id, gender, age, address, phones, mails, gender, age, hair_color
FROM persons
WHERE
name = ? AND
id = ? AND
gender = ? AND
age = ?
''', (name_input, id_input, gender_input, age_input))
You could create the WHERE clause dynamically:
sql = "SELECT ... WHERE 1"
parameters = []
if name_input != "":
sql += " AND name = ?"
parameters += [name_input]
if id_input != "":
sql += " AND id = ?"
parameters += [id_input]
...
Alternatively, rewrite the WHERE clause so that empty values are ignored:
SELECT ... WHERE (name = ?1 OR ?1 = '') AND (id = ?2 OR ?2 = '') AND ...
(?n specifies the n-th parameter.)