【问题标题】:mysql forloop in select statement in pythonpython中select语句中的mysql for循环
【发布时间】:2019-02-23 15:56:24
【问题描述】:

我有日期列表

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 的单个日期。 for 循环中的 Mysql 不起作用。没有错误,但数据没有写入。我在 for 循环之外编写了 with 函数,但没有数据写入 csv。

请帮帮我

【问题讨论】:

  • 我认为在这种情况下您不需要循环。难道你不能在日期列表中找到所有日期的位置吗?您还应该参数化查询以防止 SQL 注入等。
  • @DanielGale:在 sql 语句中,它们是从列表中的日期派生的天数(0 到 6)。这就是我尝试使用 for 循环的原因。你能帮忙吗

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


【解决方案1】:

两个选项。

选项 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 语句的更安全、更快的方式)

【讨论】:

  • 这对我没有帮助,因为它必须通过 forloop 编写,因为它们是包含在 sql 语句中的其他语句,例如基于日期的天数。
  • 你能帮我完成for循环吗?用条件纠正问题。
  • 如果您需要保留for 循环,只需使用选项1。只需将w 更改为a。仅此而已。
  • @pablojavierpy:他们的写作模式没有问题。如果我在代码中打印过去的账单。它返回给我的结果是空的。
猜你喜欢
  • 2014-11-29
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
相关资源
最近更新 更多