簡體   English   中英

如何使用python執行此sql查詢

[英]How to execute this sql query using python

追溯(最近一次通話):

模塊中的文件“ testtrans.py”,第26行

cursor1.execute(sql_query)psycopg2.ProgrammingError:

輸入LINE 1末尾的語法錯誤:

...陽離子where created_date <= DATE(NOW()-間隔'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()

我嘗試了許多方案來使此行可執行,但沒有用。

我不確定這一點,但是您代碼中的命令DATE應該是sql函數,因為它看起來像python變量/函數。 即使我錯了,圓括號也不會關閉,並且末尾還有一個額外的“。請嘗試:

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個月”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM