2017-03-18 12 views
0

私はpythonを使用してSQLデータベースを照会し、datetime(この場合は過去5分間の任意のエントリ)を使用してクエリを選択しようとしています。私は奇妙な構文エラーを取得しており、構文が間違っている理由を理解できません。 This postは近いですが、それでも問題の解決には役立ちません。日時SQLの選択エラー

エラー:

Traceback (most recent call last): 
     File "file.py", line 20, in <module> 
     cur.execute("SELECT * FROM DATA where timestamp between {} and {};".format(fiveMinutesAgo, currentTimestamp)) 
    psycopg2.ProgrammingError: syntax error at or near "13" 
    LINE 1: ...M DATA where timestamp between 2017-03-18 13:04:31.1... 
                 ^

コード:

import psycopg2 
    import datetime 

    conn = psycopg2.connect(#database credentials) 

    cur = conn.cursor() 


    currentTimestamp = datetime.datetime.now() 
    fiveMinutesAgo = datetime.datetime.now() - datetime.timedelta(minutes=5) 

    cur.execute("SELECT * FROM DATA where timestamp between {} and {};".format(fiveMinutesAgo, currentTimestamp)) 

    for record in cur: 
     print(record) 

印刷データベースのタイムスタンプ列の10のエントリ:

(datetime.datetime(2016, 12, 2, 10, 41, 8, 727398),) 
    (datetime.datetime(2016, 12, 2, 10, 41, 12, 888281),) 
    (datetime.datetime(2016, 12, 2, 10, 42, 5, 139231),) 
    (datetime.datetime(2016, 12, 2, 10, 42, 8, 536972),) 
    (datetime.datetime(2016, 12, 2, 10, 42, 11, 633446),) 
    (datetime.datetime(2016, 12, 2, 10, 43, 7, 425955),) 
    (datetime.datetime(2016, 12, 2, 10, 43, 12, 364544),) 
    (datetime.datetime(2016, 12, 2, 10, 43, 17, 623814),) 
    (datetime.datetime(2016, 12, 2, 10, 44, 4, 142015),) 
    (datetime.datetime(2016, 12, 2, 10, 44, 7, 719680),) 

すべてのヘルプは歓迎です!

+0

互換性のないデータベースタグを削除しました。実際に使用しているデータベースにタグを付けてください。 –

答えて

1

formatを使用して、SQL文に値を注入することはありません。プレースホルダを使用:

cur.execute("SELECT * FROM DATA where timestamp between %s and %s", (fiveMinutesAgo, currentTimestamp)) 
関連する問題