python sql 日期查询_如何使用日期范围在python拉/查询数据在mySQL

bd96500e110b49cbb3cd949968f18be7.png

How can I pull data in mySQL by day using python date?

Say I want day1 and day2 ( or a day after day1 ) iterate for n times

So I need the date in "where" SQL statement to look like below list in each iteration (n times )

day1 >= '2012-01-01' and day2 < '2012-01-02' ( n = 1 )

day1 >= '2012-01-02' and day2 < '2012-01-03' ( n = 2 )

.

.

day1 >= yesterday and day2 < today ( n times )

.

Start_date = '2012-01-01'

End_date = Today()

So as to write:

for each iteration ..

con.execute("select * from table where date >= day1 and date < day2" )

解决方案

You need to datetime module:-

import datetime

start = datetime.date(2012,01,01)

next = start + datetime.date.resolution

while next <= datetime.date.today():

print start, next

con.execute("""

select * from table where date >= %s and date < %s

""", (start, next))

start = next

next = start + datetime.date.resolution

IMPORTANT NOTICE: I updated the answer to fix a serious problem. Never ever use string formatting (a.k.a. %) for building SQL queries since it is open to serious problems including SQL injection. Use Python- api where nearly all RDMBes offers the same syntax

execute("select * from blah where x=%s AND y=%s", (x, y))

^ ^ ^

1 1 2

1] No quote,

2] No string formatting

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 SQL 语句的 `WHERE` 子句来编写多个条件查询 MySQL 数据库。以下是一个示例 SQL 查询,该查询使用 `AND` 运算符来组合两个条件: ```sql SELECT * FROM table_name WHERE column1 = 'value1' AND column2 = 'value2'; ``` 这将返回符合两个条件的行,其 `table_name` 是你要查询的表名,`column1` 和 `column2` 是你要匹配的列名,`value1` 和 `value2` 是你要匹配的值。 如果你想使用 `OR` 运算符而不是 `AND`,可以使用以下 SQL 查询: ```sql SELECT * FROM table_name WHERE column1 = 'value1' OR column2 = 'value2'; ``` 这将返回符合任一条件的行。 在 Python ,你可以使用 MySQL Connector 模块来连接到 MySQL 数据库并执行查询。以下是一个示例 Python 脚本,该脚本使用 MySQL Connector 模块来查询数据库: ```python import mysql.connector # 连接到 MySQL 数据库 db = mysql.connector.connect( host="localhost", user="username", password="password", database="database_name" ) # 获取游标 cursor = db.cursor() # 执行 SQL 查询 query = "SELECT * FROM table_name WHERE column1 = 'value1' AND column2 = 'value2';" cursor.execute(query) # 获取查询结果 result = cursor.fetchall() # 打印查询结果 for row in result: print(row) # 关闭游标和数据库连接 cursor.close() db.close() ``` 在此示例,`mysql.connector.connect()` 方法用于连接到 MySQL 数据库,`cursor.execute()` 方法用于执行 SQL 查询,`cursor.fetchall()` 方法用于获取查询结果。你需要将 `host`、`user`、`password` 和 `database` 参数替换为你的 MySQL 服务器信息和数据库名称,并将 `query` 变量替换为你的 SQL 查询
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值