Windowsからpythonを使って外部サーバ上のPostgreSQLに接続する

Windowsから外部のPostgreSQLサーバにpycopg2を使って接続する

準備
 python2.6をインストール
 psycopg2 for Winをインストール
  http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.2.1.win32-py2.6-pg8.4.3-release.exe

テストスクリプト

# coding:shift_jis

import psycopg2
   
try:
    conn = psycopg2.connect(database="telphone", user="dbuser", host = "192.168.0.1", port = 5432,  password="dbpass");
    print "Connected\n"
except:
    print "Can not connect\n"

cur = conn.cursor()
sql = """select num,name from tel_person where name is not null limit 200"""
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
  print row[0],':',unicode(row[1],"EUC_JP")