在python中写了一个片段,它从数据库中提取数据并将它们显示在python shell上。但是我犯了一些愚蠢的错误,因为我只得到一个日期而不是一个范围内的日期。 我的代码如下:
# open a database connection
connection = MySQLdb.connect ()
# prepare a cursor object using cursor() method
cursor = connection.cursor ()
# execute the SQL query using execute() method.
cursor.execute ()
data = cursor.fetchall()
ddt = sorted(set(data))
def dte():
for row in ddt:
date = (' '.join(map(str,row)))
return date
print dte()
这是我得到的输出:2017-11-09 但相反,我应该在一个范围内获得多个日期,例如:2017-06-17,2017-06-18等等。
答案 0 :(得分:0)
你只是在每个日期无所事事地循环,最后,你将返回最后一个。
# open a database connection
connection = MySQLdb.connect ()
# prepare a cursor object using cursor() method
cursor = connection.cursor ()
# execute the SQL query using execute() method.
cursor.execute ()
data = cursor.fetchall()
ddt = sorted(set(data))
def dte():
dates = [] #Here you need to store the dates in a list or something
for row in ddt:
dates.append(' '.join(map(str,row))) #Then append them to the list
return(dates) #Finally return them EDITED
for i in dte(ddt):
print(i)
还有一件事,使用
ddt
作为参数。这样可以避免范围问题。
像:
def dte(data):
dates = [] #Here you need to store the dates in a list or something
for row in data:
dates.append(' '.join(map(str,row))) #Then append them to the list
return(dates) #Finally return them
for i in dte(ddt):
print(i)
答案 1 :(得分:0)
return
内的函数本身不要print date
而是for
。
# open a database connection
connection = MySQLdb.connect ()
# prepare a cursor object using cursor() method
cursor = connection.cursor ()
# execute the SQL query using execute() method.
cursor.execute ()
data = cursor.fetchall()
ddt = sorted(set(data))
def dte():
for row in ddt:
date = (' '.join(map(str,row)))
print(date)
dte()