Python-PostgreSQL: psycopg2

2017-08-23  本文已影响0人  青鱼之鱼

Psycopg 是 Python 中最常用的用于操作 PostgreSQL 的库, 主要突出的是线程的安全问题(多个线程可以共用同一个连接), 设计的初衷是为了应对较重的并发操作.

Psycopg2 更突出服务器端游标(cursor)和客户端之间的游标(cursors), 异步通信和通知, 以及对 COPY TO/FROM 的支持.

Install Library

pip install psycopg2

Connect To PostgreSQL

conn=psycopg2.connect(database='dbname',user='username',password='passwd', host='hostaddr', port='port')

Create Cursor

cursor=conn.cursor()

Execute SQL

cursor.execute(SQLString)

Fetch Records

# IF excuted sql returns records, use cursor.fetchall() can get all the records.
records=cursor.fetchall()

Commit

conn.commit() # Commit the change on the transaction

Close Connection

cursor.close() # Close cursor

conn.close() # Close connection
上一篇 下一篇

猜你喜欢

热点阅读