将多个条目解包为 Python 中“字段”的字符串 3
Unpacking multiple entries as a string for `fields` in Python 3
我正在制作一个辅助函数文件来与本地数据库交互,以允许以编程方式与数据库交互。
我有两个功能:
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
我想知道如何允许 select_from_table
中的 fields
参数有多个条目,这些条目将代表后端数据库中的列(请参阅此处卡住)
例如,我试图实现的这个函数的使用示例是:我想使用 select_from_table()
执行:
select_from_table([id, name, address], person)
从 person
table.
中选择 id
、name
和 address
谢谢
您只是在尝试使用 *args
。您可以执行以下操作:
def select_from_table(table, *fields):
query = "SELECT {} FROM {}".format(",".join(fields), table)
dbcursor.execute(query)
有关 *args
和 **kwargs
的更多信息,请在此处查看此问题 *args and **kwargs?
我正在制作一个辅助函数文件来与本地数据库交互,以允许以编程方式与数据库交互。
我有两个功能:
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
我想知道如何允许 select_from_table
中的 fields
参数有多个条目,这些条目将代表后端数据库中的列(请参阅此处卡住)
例如,我试图实现的这个函数的使用示例是:我想使用 select_from_table()
执行:
select_from_table([id, name, address], person)
从 person
table.
id
、name
和 address
谢谢
您只是在尝试使用 *args
。您可以执行以下操作:
def select_from_table(table, *fields):
query = "SELECT {} FROM {}".format(",".join(fields), table)
dbcursor.execute(query)
有关 *args
和 **kwargs
的更多信息,请在此处查看此问题 *args and **kwargs?