python - python中select语句中的mysql for循环

标签 python python-2.7 for-loop mysql-python

我有日期列表

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 语句的更安全、更快速的方法)

关于python - python中select语句中的mysql for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52406466/

相关文章:

Python ndimage : Converting an existing ndarray into greyscale

python - %xP在python中是什么意思?

javascript - 对毫秒数组求和

java - Java中线程错误异常

python - 我将如何使用 boto3 在 s3 存储桶上的 aws 文件上传成功响应?

python - 超时后 Tornado future 结果

python - 我的分割序列代码有什么问题

python - 如何使用首字母缩写词命名变量?

amazon-web-services - AWS Lambda - Body Size is Too Large 错误,但 Body Size is Under Limit

Scala 向下还是 for 循环递减?