From: | "Massa, Harald Armin" <chef(at)ghum(dot)de> |
---|---|
To: | Adrian Klaver <aklaver(at)comcast(dot)net> |
Cc: | pgsql-general(at)postgresql(dot)org, Kynn Jones <kynnjo(at)gmail(dot)com> |
Subject: | Re: How to send multiple SQL commands from Python? |
Date: | 2009-10-11 00:48:39 |
Message-ID: | e3e180dc0910101748x5bdc6e8au67f62a5ad8db990c@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
Adrian,
While I was walking the dog I thought of a better solution.
>
> sql_str = """ALTER TABLE %(xn)s OWNER TO xdev;
> GRANT ALL ON TABLE %(xn)s TO xdev;
> REVOKE ALL ON TABLE %(xn)s FROM PUBLIC;
> GRANT SELECT ON TABLE %(xn)s TO PUBLIC;"""
>
> cur.execute(sql_str,{'xn':table_name})
> --
>
This will not work.
Because: "xn" will be escaped as "data", that is... the resulting string
will be:
ALTER TABLE E'waschbaer' ONER TO xdev;
which obviously is not what you want.
You can do
sql=sql_str % dict(xn=table_name)
and after taht
cur.execute(sql)
be aware that there is no quoting; so there is the danger of SQL injection,
table_name should not come from outside.
Mutliline strings are easy in Python by using triple-quoting:
sql_str = """ALTER TABLE %(xn)s OWNER TO xdev;
GRANT ALL ON TABLE %(xn)s TO xdev;
REVOKE ALL ON TABLE %(xn)s FROM PUBLIC;
GRANT SELECT ON TABLE %(xn)s TO PUBLIC;"""
With psycopg2 there is also the cursor-attribute "query", so with:
print cur.query
you can see the query actually passed to PostgreSQL (with %(whatever)s
replaced by psycopg2s calls to libpq)
Harald
--
GHUM Harald Massa
persuadere et programmare
Harald Armin Massa
Spielberger Straße 49
70435 Stuttgart
0173/9409607
no fx, no carrier pigeon
-
%s is too gigantic of an industry to bend to the whims of reality
From | Date | Subject | |
---|---|---|---|
Next Message | Adrian Klaver | 2009-10-11 01:27:08 | Re: How to send multiple SQL commands from Python? |
Previous Message | Randal L. Schwartz | 2009-10-10 22:41:27 | Re: What's wrong with this regexp? |