Я использую операторы SQL для поиска строк в моей базе данных в зависимости от заданных данных. если столбцы (ID, Имя пользователя, Пароль, Распродажа, Class_Count), тогда моя программа будет иногда искать только имя пользователя или разрешение. Но иногда он будет искать как имя пользователя, так и количество классов. Мне неизвестны какие-либо способы, с помощью которых я могу легко реализовать это в своем коде, не создавая (я полагаю) около 7 различных операторов IF, чтобы проверить, какие данные используются для поиска (примеры будут приведены в следующем коде)
def Get_Users_DB(self, Search_Data):
Details_Dic = Create_User_Dict((None,Search_Data[0],None,Search_Data[1],Search_Data[2]))
try: # Defensive programming to prevent database errors from stopping the program from running
with global_lock:
if Details_Dic["Username"]:
# If a username is given, no other values need to be checked as username are unique
self.DB_Cursor.execute("SELECT * FROM USERS WHERE username = ?", (Details_Dic["Username"],))
# Selects user from USERS table based on the username provided
User_Data = self.DB_Cursor.fetchall()
# Fetches the user if applicable, returns as a list for processing purposes
elif Details_Dic["Clearance"] and Details_Dic["Class_Count"] is not None:
print("Here b0ss")
# If there is a value for clearance and Class_Count is not a none type
self.DB_Cursor.execute("SELECT * FROM USERS WHERE\
clearance = ? AND Class_Count = ?",
(Details_Dic["Clearance"], Details_Dic["Class_Count"]))
# Select all users based on these restrictions
User_Data = self.DB_Cursor.fetchall()
elif Details_Dic["Clearance"]: # If only a clearance level is given
self.DB_Cursor.execute("SELECT * FROM USERS WHERE\
clearance = ?", (Details_Dic["Clearance"],))
User_Data = self.DB_Cursor.fetchall()
elif Details_Dic["Class_Count"] is not None: # If only a class value is given
self.DB_Cursor.execute("SELECT * FROM USERS WHERE\
Class_Count = ?", (Details_Dic["Class_Count"],))
User_Data = self.DB_Cursor.fetchall()
else: # If no values are given, get all users
self.DB_Cursor.execute("SELECT * FROM USERS")
User_Data = self.DB_Cursor.fetchall()
if User_Data: # If any value was returned from the database
User_Dict_List = []
for User_Details in User_Data: # For every user in the list convert them to a dictionary
User_Dict = Create_User_Dict(User_Details)
User_Dict_List.append(User_Dict)
return User_Dict_List
else:
return False # Tell called from function that the user does not exist
except sqlite3.Error as Err: # If an error occurs display a message in the console
Error_Report(Err, "Get_User_DB")
return False # Tell called from function that the function was unsuccessful
Из этой программы я в основном хочу более упорядоченный способ проверки того, какие данные предоставлены, и что мне нужно для запроса моей базы данных с помощью
Edit:
Я сейчас попробовал метод при условии:
def Create_Where_Condition(self, Details_Dic):
print("In Where Condition")
Where_Condition = ""
for Key, Value in Details_Dic.items():
print("Key:",Key)
print("Value:", Value)
if Value is not None:
Prefix = " AND " if Where_Condition else " WHERE "
Where_Condition += Prefix + "{}={}".format(Key, Value)
return Where_Condition
def Get_Users_DB(self,Search_Data):
print("In get_user_db")
Details_Dic = Create_User_Dict((None, Search_Data[0], None, Search_Data[1], Search_Data[2]))
print("after details_dic")
SQL_Statement = "SELECT * FROM USERS" + self.Create_Where_Condition(Details_Dic)
print("SQL STATEMENT:\n{}".format(SQL_Statement))
try: # Defensive programming to prevent database errors from stopping the program from running
with global_lock:
self.DB_Cursor.execute(SQL_Statement)
User_Data = self.DB_Cursor.fetchall()
print(User_Data)
if User_Data: # If any value was returned from the database
User_Dict_List = []
for User_Details in User_Data: # For every user in the list convert them to a dictionary
User_Dict = Create_User_Dict(User_Details)
User_Dict_List.append(User_Dict)
return User_Dict_List
else:
return False # Tell called from function that the user does not exist
except sqlite3.Error as Err: # If an error occurs display a message in the console
Error_Report(Err, "Get_User_DB")
return False # Tell called from function that the function was unsuccessful
Однако теперь я получаю ошибку:
sqlite3.OperationalError: no such column: foo
где 'foo' - это имя пользователя, которое я ищу