【问题标题】:Invalid Syntax (near date)无效语法(接近日期)
【发布时间】:2017-11-13 10:21:18
【问题描述】:

我在 stackoverflow 中找到了这段代码。符合我的要求。我正在使用一个由 id、日期、性别、姓名和姓氏组成的 mysql 数据库。我对代码做了一些更改,以便我可以获得开始日期和结束日期之间的日期和其他信息。

import mysql
import mysql.connector
import command
import datetime

def findarbs(startdate, enddate):
      con = mysql.connector.connect(user='root', password='root', 
host='localhost',port='3306',database='testdb')
      cur = con.cursor()
      command = ("SELECT DISTINCT id, date FROM babyrop", WHERE 'date1' 
      > ('%s') AND 'date2' < ('%s'), ORDER BY date asc % (startdate, 
enddate))
print ('command')
cursor.execute(command)
result = cur.fetchone()
print (result)
while result is not None:
print (result[1])
result = cursor.fetchone()
cur = con.cursor()
cur.execute('select id, date weight from babyrop')

data = cursor.fetchall()
cur.close()
con.close()

当我尝试执行它时,我在日期附近收到错误“无效语法”。让我知道需要进行哪些更正。

【问题讨论】:

  • 你完全搞乱了command 字符串。

标签: python mysql datetime


【解决方案1】:
  1. 您过早地终止了字符串。查询中的逗号也无效。

    command = ("SELECT DISTINCT id, date FROM babyrop", WHERE 'date1' 
          > ('%s') AND 'date2' < ('%s'), ORDER BY date asc % (startdate, 
    enddate))
    

    “应该”是

        command = ("SELECT DISTINCT id, date FROM babyrop WHERE 'date1' 
      > ('%s') AND 'date2' < ('%s') ORDER BY date asc" % (startdate, 
    enddate))
    
  2. 我写“应该”是因为您应该不在查询中使用字符串连接,因为它会将您的代码暴露给 SQL 注入。您应该改用参数化查询。还建议对查询字符串使用三引号,以便很好地将它们分开:

        command = """SELECT DISTINCT id, date
                     FROM babyrop
                     WHERE 'date1' > ('%s') AND 'date2' < ('%s')
                     ORDER BY date asc"""
    
        cursor.execute(command, (startdate, enddate))
    

    另外,我很确定您不需要在 where 子句中的列名和占位符周围加上单引号 ('),但这可能是 MySQL 的问题。

【讨论】:

  • 嘿,我尝试做你提到的更改,但收到以下错误
  • Traceback(最近一次调用最后):文件“C:/Users/Shalini/Desktop/wenzins/13th nov/pyhton+mysql between.py”,第 12 行,在 cursor.execute (command,(startdate, enddate)) NameError: name 'cursor' is not defined
  • 你在我复制粘贴的代码中使用了cursor,但它应该是cur。
  • 我将光标替换为 cur 并出现以下错误
  • Traceback(最近一次调用最后):文件“C:\Users\Shalini\Desktop\wenzins\13th nov\pyhton+mysql between.py”,第 12 行,在 cur.execute (command) NameError: name 'cur' is not defined
猜你喜欢
  • 2018-12-12
  • 2014-06-26
  • 2021-05-06
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多