0

I am streaming tweets to a postgres database with a python script (using psycopg2). I would like to be able to schedule this script in a windows task manager. The only issue I have to overcome is to be able to rename the table in postgres. Is it possible?

x = datetime.date.today() - datetime.timedelta(days=1)
con = psycopg2.connect("dbname='test' user='postgres'")   

cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS schemaname.%s", (x))

** UPDATE

That answer does get my further, now it just complains about the numbers.

Traceback (most recent call last):
File "Z:/deso-gis/scripts/test123.py", line 26, in <module>
cur.execute("DROP TABLE IF EXISTS tweets_days.%s" % x)
psycopg2.ProgrammingError: syntax error at or near ".2016"
LINE 1: DROP TABLE IF EXISTS tweets_days.2016-02-29

1 Answer 1

1

I believe you are getting arror at line

cur.execute("DROP TABLE IF EXISTS schemaname.%s", (x))

because psycopg generates not what you want:

DROP TABLE IF EXISTS schemaname."table_name"

try using

cur.execute("DROP TABLE IF EXISTS schemaname.%s" % x)

This is not as secure as could be but now table name is name not SQL string.

Sign up to request clarification or add additional context in comments.

5 Comments

I tried your answer and it got me further, not yet there though. My question is updated.
I figured it out. I had to add " to the statement, like how postgres likes it. The following line did the trick. cur.execute("DROP TABLE IF EXISTS tweets_days."'"%s"'"" % x)
@Zuenie Use triple quotes to avoid escaping mess: '''DROP TABLE IF EXISTS tweets_days."%s"''' % x
I recommend to change a little bit table name: cur.execute("DROP TABLE IF EXISTS schemaname.%s" % str(x).replace('-', '_')) so there is no special chars in name and you don't have to quote them at all.
man stackoverflow is awesome. I used the two tips in the comments here and its running perfectly now :) thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.