18

ローカルマシンで実行しているだけのpostgresqlデータベースで使用しようとしてpsycopg2いますが、何を試しても結果を返すことができません。構成パラメーターのいずれかを変更するとエラーがスローされるため、データベースに正常に接続しているように見えますが、一見有効で結果に値するクエリを実行すると、何も得られません。

私のデータベースは実行されており、間違いなくその中にテーブルがあります:

postgres=# \c
You are now connected to database "postgres" as user "postgres".
postgres=# select * from foos;
  name   | age 
---------+-----
 Sarah   |  23
 Michael |  35
 Alice   |  12
 James   |  20
 John    |  52
(5 rows)

私のpythonコードはこのデータベースに接続しますが、実行するクエリに関係なく、次のようになりますNone:

Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost'")
>>> cur = conn.cursor()
>>> print cur.execute("select * from foos;")
None
>>> print cur.execute("select * from foos")
None
>>> print cur.execute("select name from foos")
None
>>> print cur.execute("select f.name from foos f")
None

私は明らかに間違ったことをしていますか?これのデバッグを開始するにはどうすればよいですか? 問題なく接続されているため、どこから開始すればよいかわかりません。

4

4 に答える 4

4

カーソルのexecute()メソッドは、渡された SQL を実行するだけです。次に、カーソルから応答を取得するためのオプションがいくつかあります。fetchone()次の結果を返すメソッドを使用できます。初めて呼び出す場合は最初の結果が得られ、2 回目は 2 番目の結果が得られます。このfetchall()メソッドはすべての行を返し、反復子として使用できます。

例:

>>> # This is an example of the fetchone() method
>>> cur.execute("select * from foos")
>>> # This call will return the first row 
>>> result = cur.fetchone()
>>> # This call will return the second row
>>> result = cur.fetchone()


>>> # This is an example of the fetchall() method
>>> cur.execute("select * from foos")
>>> results = cur.fetchall()
>>> for r in results:
...     print r
>>> # Now we'll reset the cursor by re-executing the query
>>> cur.execute("select * from foos")
>>> for r in cur.fetchall():
...     print r
于 2013-09-30T16:07:02.317 に答える
4

ドキュメントに記載されているように、注意してください:http://initd.org/psycopg/docs/cursor.html「カーソルオブジェクトは反復可能であるため、ループで明示的に fetchone() を呼び出す代わりに、オブジェクト自体を使用できます」

したがって、次のように書くことも同様に有効です。

>>> cur.execute("select foo, bar from foobars")
>>> for foo, bar in cur:
....    print foo, bar

fetchone() を明示的に呼び出さずに。私たち pythonistas は、理解を損なわない限り、簡潔なコードを好むはずであり、私見では、これはより自然に感じられます。

于 2014-03-07T09:23:54.823 に答える