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
Zuenie
  • 963
  • 2
  • 11
  • 30

1 Answers1

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.

omikron
  • 2,745
  • 1
  • 25
  • 34
  • I tried your answer and it got me further, not yet there though. My question is updated. – Zuenie Mar 01 '16 at 11:04
  • 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 Mar 01 '16 at 11:07
  • @Zuenie Use triple quotes to avoid escaping mess: `'''DROP TABLE IF EXISTS tweets_days."%s"''' % x` – Clodoaldo Neto Mar 01 '16 at 13:39
  • 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. – omikron Mar 01 '16 at 14:40
  • man stackoverflow is awesome. I used the two tips in the comments here and its running perfectly now :) thanks a lot! – Zuenie Mar 01 '16 at 15:38