在 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 等等。
你只是循环每个日期什么都不做,最后,你返回最后一个。
# 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句