如何使用select now()导致Python中的另一个查询?

时间:2016-01-08 11:20:41

标签: python mysql

我想在另一个查询中使用select now()查询结果,但是我无法这样做。

我的代码:

import MySQLdb 

db = MySQLdb.connect(host,username,password,databasename)

cursor = db.cursor()

cursor.execute("SELECT NOW()")

dt = cursor.fetchone()

dt = str(dt) #1

cursor2 = db.cursor()

sql2 = "SELECT pid from PRODUCTS where date between DATE_SUB(" + dt + ", INTERVAL 2 HOUR) and " + dt  #... query2

cursor2.execute(sql2)

如何使用#query2中#1中的日期。它给了我错误。

我甚至使用DATE_FORMAT函数将其转换为SQL中的NOW()函数给出输出的相同格式。然后尝试在SQL查询中使用它。但它仍然给我语法错误。

3 个答案:

答案 0 :(得分:1)

您可以尝试在相应日期使用%s

sql2 = "SELECT pid from PRODUCTS where date between DATE_SUB(%s, INTERVAL 2 HOUR) and %s"

cursor2.execute(sql2,(dt,dt))

答案 1 :(得分:1)

MySQLdb会自动将MySQL日期时间转换为Python本地datetime.datetime对象,并将Python本地datetime.datetime对象转换为MySQL正确的日期时间,因此您不需要进行任何转换/格式化或任何操作靠自己。只需正确使用db api:

即可
import MySQLdb 
db = MySQLdb.connect(host,username,password,databasename)
cursor = db.cursor()
cursor.execute("SELECT NOW()")
dt = cursor.fetchone()[0] # fetchone returns a tuple
print dt # should print a `datetime.datetime` object

# no need for a second cursor here now you have fetched results
# from your previous query
#cursor2 = db.cursor()

# **ALWAYS** use your db connector's placeholders 
sql2 = "SELECT pid from PRODUCTS where date between DATE_SUB(%s, INTERVAL 2 HOUR) and %s"

# this way your db connector will take care of proper transformation / formatting / sanitization / escaping etc
cursor.execute(sql2, (dt, dt))

答案 2 :(得分:0)

此链接可能很有用,请试试!:

https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html 这是它的内容:

“任务是选择1999年雇用的所有员工,并将他们的姓名和雇用日期打印到控制台。”

import datetime
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

query = ("SELECT first_name, last_name, hire_date FROM employees "
         "WHERE hire_date BETWEEN %s AND %s")

hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)

cursor.execute(query, (hire_start, hire_end))

for (first_name, last_name, hire_date) in cursor:
  print("{}, {} was hired on {:%d %b %Y}".format(
    last_name, first_name, hire_date))

cursor.close()
cnx.close()