DEV Community

loading...
Cover image for Postgress SELECT/INSERT in Python without any external libs

Postgress SELECT/INSERT in Python without any external libs

yne profile image Rémy F. ・1 min read

It is possible to query Postgress (9.3+) from python without any external libs (psycopg2):

import subprocess
import json

query = "SELECT json_agg(table) FROM table"
args = ["psql", "base" ,"user" ,"-AStc", query]
out = subprocess.check_output(args, universal_newlines=True)
results = json.loads(out)
print(results)

It is also possible to INSERT with

data = {
  "question": "when does the ride end ?",
  "answer": "never",
  "category": 1
}

cols = ','.join(''.join(filter(str.isalpha, k)) for k in data.keys())
query = "INSERT INTO tb_faq(%s) SELECT %s FROM json_populate_record(NULL::tb_faq, '%s');"
args = ["psql", "vbox" ,"boxadmin" ,"-AStc", query%(cols,cols,json.dumps(data))]
subprocess.check_output(args, universal_newlines=True)

Discussion (0)

pic
Editor guide