简体   繁体   中英

How to execute this sql query using python

Traceback (most recent call last):

File "testtrans.py", line 26, in module

cursor1.execute(sql_query) psycopg2.ProgrammingError:

syntax error at end of input LINE 1:

...cation where created_date <= DATE(NOW() - interval '1 month'

import time
import pandas as pd
import sqlalchemy
from sqlalchemy import create_engine
import psycopg2
from sqlalchemy.types import TIMESTAMP as typeTIMESTAMP

connection1 = psycopg2.connect("host='localhost1' dbname='prod' user='root' password='pass1'")
 cursor1 = connection1.cursor()

engine1 =   create_engine('postgresql://root:localhost1:5432/prod')
engine2 = create_engine('postgresql://root:localhost1:5432/prod_archive')

df = pd.read_sql_query("""
select id,text,created_date,is_read,to_user_id,is_new,url,text_ar,text_en from notifications_notification where created_date <= NOW() - interval '1 month'
""",engine1)
df= df.rename(columns={
'id':'original_id','text':'text','created_date':'created_date','is_read':'is_read','to_user_id':'to_user_id','is_new':'is_new','url':'url','text_ar':'text_ar','text_en':'text_en'  
})

df['created_date'] = pd.to_datetime(df['created_date'])
df['created_date'] = df['created_date'].astype('datetime64[us]')
df.set_index('created_date', inplace=True)
#df.to_sql(name='notifications_notification_archive',con=engine2,if_exists='append')
sql_query = "delete from notifications_notification where id in (select id from notifications_notification where created_date <= "DATE(NOW() - interval '1 month'""
cursor1.execute(sql_query)
connection1.commit()

I tried many scenarios to make this line executable but it didn't work.

I am not sure about this one, but the command DATE in your code should be a sql function and as it is it looks like a python variable/function. Even if I am wrong, the parentheses are not closed and there is an extra " at the end. Try:

sql_query = "delete from notifications_notification where id in (select id from notifications_notification where created_date <= DATE(NOW())" - interval '1 month'"

从notifications_notification中的id删除(从notifications_notification中的id选择create_date <= NOW()-间隔“ 1个月”)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM