我有日期清单
datefromto=['2018-06-16','2018-08-10','2018-09-12']
选择查询应查询给定日期并存储在csv文件中
for dates in datefromto:
yesterbilling="""select * from student_date where date(datetime)= """+str(dates)+""" and daynumber="""+str(time.strftime("%w", time.strptime(dates, "%Y-%m-%d")))+""" and status='attended' """
cursor.execute(yesterbilling)
yesterbillings = cursor.fetchall()
myFile = open(students.csv, 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(yesterbillings)
print("Writing complete")
这适用于没有forloop的单个日期。 MySQL for循环内部无法正常工作。没有错误,但未写入数据。我在for循环外部编写了with函数,但是没有在CSV中写入任何数据。
请帮帮我
参考方案
两种选择。
选项1:在每个使用a
的循环期间,使用w
进行附加而不是覆盖。像这样:
myFile = open(students.csv, 'a')
选项2(更好):像这样使用SQL的in
子句:
yesterbilling="select * from student_date where date(datetime) in ('" + "','".join(datefromto) + "') and status='attended' "
cursor.execute(yesterbilling)
yesterbillings = cursor.fetchall()
# now it's safe to use 'w' because the writing will be done at once
myFile = open(students.csv, 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(yesterbillings)
还有一件事:如果您的python字符串不会跨越多行,则不需要"""
。只需使用一个"
。
另外,学习如何使用:
Python string format
带参数的sql语句(将参数传递到SQL语句的更安全,更快捷的方法)
我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
Python-crontab模块 - python我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
查找字符串中的行数 - python我正在创建一个python电影播放器/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …
字符串文字中的正斜杠表现异常 - python为什么S1和S2在撇号位置方面表现不同?S1="1/282/03/10" S2="4/107/03/10" R1="".join({"N\'" ,S1,"\'" }) R2="".join({"N\'…