To insert to Pg by Psycopg

594 views Asked by At

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
2

There are 2 answers

3
bobince On BEST ANSWER

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.

0
Denis Otkidach On

You have to call cur.fetchall() method (or one of other fetch*() methods) to get results from query.