Execute .sql schema in psycopg2 in Python

2024/11/19 17:34:25

I have a PostgreSQL schema stored in .sql file. It looks something like:

CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,facebook_id TEXT NOT NULL,name TEXT NOT NULL,access_token TEXT,created INTEGER NOT NULL
);

How shall I run this schema after connecting to the database?

My existing Python code works for SQLite databases:

# Create database connection
self.connection = sqlite3.connect("example.db")# Run database schema
with self.connection as cursor:cursor.executescript(open("schema.sql", "r").read())

But the psycopg2 doesn't have an executescript method on the cursor. So, how can I achieve this?

Answer

You can just use execute:

with self.connection as cursor:cursor.execute(open("schema.sql", "r").read())

though you may want to set psycopg2 to autocommit mode first so you can use the script's own transaction management.

It'd be nice if psycopg2 offered a smarter mode where it read the file in a statement-at-a-time and sent it to the DB, but at present there's no such mode as far as I know. It'd need a fairly solid parser to do it correctly when faced with $$ quoting (and its $delimiter$ variant where the deimiter may be any identifier), standard_conforming_strings, E'' strings, nested function bodies, etc.

Note that this will not work with:

  • anything containing psql backslash commands
  • COPY .. FROM STDIN
  • very long input

... and therefore won't work with dumps from pg_dump

https://en.xdnf.cn/q/26414.html

Related Q&A

AttributeError: module html.parser has no attribute HTMLParseError

This is the hints,how can I resolve it? I use Python 3.5.1 created a virtual envirement by virtualenv The source code works well on my friends computer machineError: Traceback (most recent call last):…

Error message python-pylint C0103:Invalid constant name

Im confused about the error(s) in this photo:I dont know how to fix them. My program is a Python-Flask web frame. When I use Visual Studio Code to debug my program, Pylint shows these errors. I know th…

How to use virtualenv with python3.6 on ubuntu 16.04?

Im using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. Ive installed Python 3.6 on it and symlink python3 to python3.6 through alias python3=python3.6.Then, Ive installed virtualenv using s…

Is a day always 86,400 epoch seconds long?

While reviewing my past answers, I noticed Id proposed code such as this:import timedef dates_between(start, end):# muck around between the 9k+ time representation systems in Python# now start and end …

Find the first instance of a nonzero number in a list in Python [duplicate]

This question already has answers here:Return the index of the first element of a list which makes a passed function true(7 answers)Closed last year.I have a list like this: myList = [0.0, 0.0, 0.0, 2.…

How to debug a Python module in Visual Studio Codes launch.json

My question may seem simple but, I have a module that I launch in a terminal like this: python -m my_module.my_fileHow do I debug this in Visual Studio Code? I have this in my launch.json (documentati…

Cleanest Fastest server setup for Django [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

Quicker to os.walk or glob?

Im messing around with file lookups in python on a large hard disk. Ive been looking at os.walk and glob. I usually use os.walk as I find it much neater and seems to be quicker (for usual size direct…

Getting PyCharm to recognize python on the windows linux subsystem (bash on windows)

While running Linux versions of python, pip etc. "natively" on windows is amazing, Id like to do so using a proper IDE. Since SSHD compatibility has not been implemented yet, Im trying get Py…

Whats the difference between nan, NaN and NAN

In numpy there are nan, NaN and NAN. Whats the sense of having all three, do they differ or any of these can be used interchangeably?