DEV Community

Cover image for Postgress SELECT/INSERT in Python without any external libs
Rémy F.
Rémy F.

Posted on • Updated on

Postgress SELECT/INSERT in Python without any external libs

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", "db_name" ,"db_user" ,"-AStc", query]
out = subprocess.check_output(args, universal_newlines=True)
results = json.loads(out)
print(results)
Enter fullscreen mode Exit fullscreen mode

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", "db_name" ,"db_user" ,"-AStc", query%(cols,cols,json.dumps(data))]
subprocess.check_output(args, universal_newlines=True)

Enter fullscreen mode Exit fullscreen mode

Discussion (0)