如何使用python执行此sql查询

时间:2019-01-07 12:38:38

标签: python scripting

回溯(最近通话最近一次):

  

文件“ testtrans.py”,第26行,在模块中

     

cursor1.execute(sql_query)psycopg2.ProgrammingError:

     输入行1末尾的

语法错误

     

...阳离子,其中created_date <= DATE(NOW()-间隔“ 1个月”

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()

我尝试了许多方案来使此行可执行,但没有用。

2 个答案:

答案 0 :(得分:0)

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'"

答案 1 :(得分:0)

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