2012年9月11日 星期二

psycopg:Python操作Postgres資料庫

官方:http://initd.org/psycopg/
下載psycopg2-2.4.5.win32-py2.7-pg9.1.3-release並安裝
(請依OS與PY版本自行選擇)

#! /usr/bin/env python
import psycopg2
try:
    conn = psycopg2.connect(host="127.0.0.1", port="5432", database="dbName", user="userName", password="userPwd")
    cur = conn.cursor()
    cur.execute("CREATE TABLE test (id serial PRIMARY KEY, name varchar);")
    cur.execute("INSERT INTO test (name) VALUES (%s)",("Lyon Lin"))
    cur.execute("SELECT * FROM test;")
    cur.fetchone()
    conn.commit()    
    print "OK"
except:
    print "I am unable to connect to the database"
finally:
    cur.close()
    conn.close()




沒有留言:

張貼留言