2

the Python db-api implementation for sqlite has a convinient method executescript() to execute multi-statement SQL scripts. It is very useful for instance for db creation. See sqlite driver documentation.

I can't find a similar one for Psycopg db-api driver for PostgreSQL. Does executescript() exist in Psycopg? Any alternative?

Thanks

3
  • Please add executescript(sql_script) here instead of referring to external link Commented Apr 24, 2018 at 15:37
  • @CharlesDuffy OK, great! This means i can do cursor.execute("sql statement1; sql statement2; etc...") Commented Apr 24, 2018 at 15:53
  • Correct. Adding an answer to that effect. Commented Apr 24, 2018 at 16:10

1 Answer 1

3

You don't need it -- a single query string can already contain multiple separate queries.

Quoting from the wire protocol documentation, emphasis added:

A simple query cycle is initiated by the frontend sending a Query message to the backend. The message includes an SQL command (or commands) expressed as a text string. The backend then sends one or more response messages depending on the contents of the query command string, and finally a ReadyForQuery response message. ReadyForQuery informs the frontend that it can safely send a new command. (It is not actually necessary for the frontend to wait for ReadyForQuery before issuing another command, but the frontend must then take responsibility for figuring out what happens if the earlier command fails and already-issued later commands succeed.)

...and later:

Since a query string could contain several queries (separated by semicolons), there might be several such response sequences before the backend finishes processing the query string. ReadyForQuery is issued when the entire string has been processed and the backend is ready to accept a new query string.


Thus, the standard cursor.execute() call can be given a semicolon-separated list of individual queries to run.

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

Comments

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.