0

DB テーブルから選択して行を反復処理するスクリプトを作成しています。

MySQL では、次のようにします。

import MySQLdb
db_mysql=MySQLdb.Connect(user=...,passwd=...,db=..., host=...)
cur = db_mysql.cursor(MySQLdb.cursors.DictCursor)
cur.execute ("""SELECT X,Y,Z FROM tab_a""")
for row in crs.fetchall () :
     do things...

しかし、PostgreSQLでそれを行う方法がわかりません。基本的に、この質問は、上記の MySQL コードを PostgreSQL で動作するように変換する方法です。

これは私がこれまでに持っているものです (私は PyGreSQL を使用しています)。

import pg
pos = pg.connect(dbname=...,user=...,passwd=...,host=..., port=...)
pos.query("""SELECT X,Y,Z FROM tab_a""")

クエリ結果を反復処理するにはどうすればよいですか?

4

2 に答える 2

0

同じだと思います。カーソルを作成し、フェッチを呼び出して、MySQL と同じように反復する必要があります。

import pgdb
pos = pgdb.connect(database=...,user=...,password=...,host=..., port=...)
sel = "select version() as x, current_timestamp as y, current_user as z"
cursor = db_conn().cursor()
cursor.execute(sel)
columns_descr = cursor.description
rows = cursor.fetchall()
for row in rows:
    x, y, z = row
    print('variables:')
    print('%s\t%s\t%s' % (x, y, z))
    print('\nrow:')
    print(row)
    print('\ncolumns:')
    for i in range(len(columns_descr)):
        print('-- %s (%s) --' % (columns_descr[i][0], columns_descr[i][1]))
        print('%s' % (row[i]))
    # this will work with PyGreSQL >= 5.0
    print('\n testing named tuples')
    print('%s\t%s\t%s' % (row.x, row.y, row.z))
于 2016-04-14T07:46:57.740 に答える