I'm making a helper function file to interact with a local database to allow interaction with the database in a programmatic way.
I have 2 functions:
import pymysql
def conn_db(host, port, user, password, database):
#conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='mysql')
conn = pymysql.connect(host=host, port=port, user=user, passwd=password, db=database)
dbcursor = conn.cursor()
return dbcursor
def select_from_table(fields, table):
#dbcursor.execute(SELECT <fields> from table)
dbcursor.execute() #STUCK HERE
I'm wondering how I can allow multiple entries for the fields
parameter in select_from_table
which would represent columns in the backend database (see STUCK HERE)
for instance, an example of a use of this function I am trying to achieve is: I want to execute using select_from_table()
:
select_from_table([id, name, address], person)
where it'd be selecting both the id
, name
, and address
from the person
table.
Thanks
You are simply trying to use *args
. You can do the following:
def select_from_table(table, *fields):
query = "SELECT {} FROM {}".format(",".join(fields), table)
dbcursor.execute(query)
For more information on *args
and **kwargs
check out this question here *args and **kwargs?