如何在Python中使用select now()生成另一个查询?

如何在Python中使用select now()生成另一个查询?,python,mysql,Python,Mysql,我想在另一个查询中使用在Python中执行的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

我想在另一个查询中使用在Python中执行的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)
如何使用查询2中1中的日期2。这给了我错误

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

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

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

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

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

以下是它的功能:

任务是选择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()

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))

这给了我错误什么错误?直接在查询中使用NOW有什么问题?ie从产品中选择pid,其中日期介于日期_子行、间隔2小时和NOW@brunodesthuilliers:这很好,但我需要在另一个查询中使用它,我没有提到,并且希望两个查询的时间相同。否则,两个查询的时间都会改变。