python连接postgreSQL

利用python(我用的是python2.7版本)连接postgresql数据库,这里使用psycopg2这个插件

官网下载psycopg2-2.5.1.tar.gz:http://initd.org/psycopg/

过程很简单,如下:

## 导入psycopg2包
import psycopg2
## 连接到一个给定的数据库
conn = psycopg2.connect(database="postgres", user="postgres",
                        password="postgres", host="127.0.0.1", port="23333")
## 建立游标,用来执行数据库操作
cursor = conn.cursor()

## 执行SQL命令
cursor.execute("DROP TABLE test_conn")
cursor.execute("CREATE TABLE test_conn(id int, name text)")
cursor.execute("INSERT INTO test_conn values(1,'haha')")

## 提交SQL命令
conn.commit()

## 执行SQL SELECT命令
cursor.execute("select * from test_conn")

## 获取SELECT返回的元组
rows = cursor.fetchall()
for row in rows:
    print 'id = ',row[0], 'name = ', row[1], '
'

## 关闭游标
cursor.close()

## 关闭数据库连接
conn.close()
原文地址:https://www.cnblogs.com/flying-tiger/p/6704696.html