在python中将两个datetime参数传递给SQL查询

时间:2017-08-09 06:02:48

标签: python sql

在不断获取MySQL 1064的同时,我一直在努力寻找此错误的解决方案。

我的代码:

$name=$_POST['name'];
$email=$_POSt['emailaddress'];

$sql='insert into `registration` ( `name`, `emailaddress` ) values ( :name, :email )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
    $stmt->bindParam(':name',$name);
    $stmt->bindParam(':email',$email);

    $stmt->execute();
}

产生以下错误:

query = "SELECT iv_alert.sensorId, iv_alert.sensorAlertUUID, 
iv_packetlog.packetData FROM iv_alert LEFT JOIN iv_packetlog ON 
iv_alert.packetLogId = iv_packetlog.packetLogId WHERE 
iv_packetlog.creationTime > %s AND iv_packetlog.creationTime <= %s"

args=lastquerytime, lasttime
cursor.execute(query,args)

同时,只传递一个参数效果很好:

_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your 
SQL syntax ; check the manual that corresponds to your MySQL server version for 
the right syntax to use near \') AND iv_packetlog.creationTime <= 
("\'2017-08-09 14:53:21\'",)\' at line 1')

我做错了什么?请指教。

2 个答案:

答案 0 :(得分:0)

尝试在查询周围添加括号,并使args成为元组:

query = ("SELECT iv_alert.sensorId, iv_alert.sensorAlertUUID,"
         "iv_packetlog.packetData FROM iv_alert LEFT JOIN iv_packetlog ON"
         "iv_alert.packetLogId = iv_packetlog.packetLogId WHERE"
         "iv_packetlog.creationTime > %s AND iv_packetlog.creationTime <= %s")

args = (lastquerytime, lasttime)
cursor.execute(query, args)

您可以在文档中看到相同的example

答案 1 :(得分:0)

好的,这是解决方案:

而不是:

args=lastquerytime, lasttime

传递这个:

args=(lastquerytime + lasttime)

使其成为一个统一的元组。