Search code examples
pythonpostgresqlpsycopg

To insert to Pg by Psycopg


How can you fix the SQL-statement in Python?

The db connection works. However, cur.execute returns none which is false.

My code

import os, pg, sys, re, psycopg2

try:
   conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'")
except: print "unable to connect to db"
cur = conn.cursor()

print cur.execute("SELECT * FROM courses")     # problem here

The SQL-command in Psql returns me the correct output. I can similarly run INSERT in Psql, but not by Python's scripts. I get no warning/error to /var/log.

Possible bugs are

  1. cursor(), seems to be right however
  2. the syntax of the method connect(), seems to be ok however

Solution

  • You have to call one of the fetch methods on cur (fetchone, fetchmany, fetchall) to actually get the results of the query.

    You should probably have a read through the a tutorial for DB-API.