views:

109

answers:

2

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  A: 

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.

bobince
**Which method do you need to run to put the data to the database?** `cur.insert("INSERT INTO courses (course) VALUES ( %s )""", [data])` is not working for me.
Masi
* I mean cur.execute
Masi
Check `psycopg.paramstyle` to see which parameterisation style you're supposed to use with that module; it is unfortunate that DB-API allows several possibilities rather than standardising on one. I *think* `psycopg` is supposed to be using `'pyformat'`, in which case `cur.execute('INSERT INTO courses (course) VALUES(%(course)s)', {'course': var})` would be the syntax.
bobince
"is not working" is a bit vague - does it raise an exception? Also, I don't think psycopg2 autocommits by default (unlike psql) - you'll need to call `conn.commit()` after inserting the row, for it to become visible to other sessions.
SimonJ
+2  A: 

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

Denis Otkidach