python pymysql 执行比较时间的sql语句,在mysql中可以顺了执行,但是在python中执行为何报错?

python版本:3.5 mysql 版本:5.6
python pymysql 执行比较时间的sql语句,在mysql中可以顺了执行,但是在python中执行报错;
数据库表为考勤打机中导出的考勤数据,根据工号筛选出迟到及早退人员;
在数据库中筛选出时间在7:30:00之后以及在17:30:00之前打卡的;


数据库表结构:

clipboard.png


以下为sql语句

select * from kaoqinjilu WHERE gonghao = 6063 and date_format(datatime,'%Y-%m-%d %H:%i:%s')>DATE_ADD(date_format(datatime,'%Y-%m-%d'),INTERVAL "7:30:00" HOUR_SECOND)
and date_format(datatime,'%Y-%m-%d %H:%i:%s')<DATE_ADD(date_format(datatime,'%Y-%m-%d'),INTERVAL "17:30:00" HOUR_SECOND);

执行结果,顺利得到结果:

clipboard.png


python代码:

import pymysql.cursors
#连接数据库
connect = pymysql.connect(host='127.0.0.1',port=3306, user='root', passwd='111111', db='test',charset='utf8',)
#获取游标
cursor = connect.cursor()

sql = "select * from kaoqinjilu WHERE gonghao = 6063 AND date_format(datatime,'%%Y-%%m-%%d %%H:%%i:%%s')>DATE_ADD(date_format(datatime,'%%Y-%%m-%%d'),INTERVAL '7:30:00' HOUR_SECOND)
and date_format(datatime,'%%Y-%%m-%%d %%H:%%i:%%s')<DATE_ADD(date_format(datatime,'%%Y-%%m-%%d'),INTERVAL '17:30:00' HOUR_SECOND)"
cursor.execute(sql)

#提交
connect.commit()

for row in cursor.fetchall():
    print(row)
print('迟到早退人数',cursor.rowcount)

报错信息:

C:\Users\gsd\AppData\Local\Programs\Python\Python35\python.exe F:/100lainxiti/考勤查询.py
  File "F:/100lainxiti/考勤查询.py", line 7
    sql = "select * from kaoqinjilu WHERE gonghao = 6063 AND date_format(datatime,'%%Y-%%m-%%d %%H:%%i:%%s')>DATE_ADD(date_format(datatime,'%%Y-%%m-%%d'),INTERVAL '7:30:00' HOUR_SECOND)
                                                                                                                                                                                        ^
SyntaxError: EOL while scanning string literal

Process finished with exit code 1
阅读 7.4k
2 个回答

多行语句试试用

""" ...... 
    ...... 
"""

进行包裹

看了楼上的评论,参见这个:https://stackoverflow.com/que...

Python里使用MySQL语句,不需要添加%来转义%,Python的MySQL模块会默认添加转义字符。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题