[备忘]Psycopg学习笔记(1)

来源:互联网 发布:软件开发工艺流程 编辑:程序博客网 时间:2024/05/22 17:43

以下内容节选翻译自Psycopy的帮助文档:(http://initd.org/psycopg/docs/),版本为:Psycopg 2.6.2.dev0

Psycopg的主入口是:connect()函数,该函数创建一个数据库会话(session),然后返回一个 connection 实例。

connection类封装了一个数据库会话(session)

  • 调用该类的cursor()函数,创建一个cursor实例,可以用来执行数据库命令、进行数据库查询操作
  • 调用该类的commit()方法,或者rollback()方法,可以终止一次处理(transaction)
cursor类允许与数据库进行交互操作

  • 通过execute()、executemany()等方法,给数据库发送命令,
  • 通过fetchone()、fetchmany()、fetchall()等方法或者通过迭代的方法,取回结果。
代码示例:

>>> import psycopg2# Connect to an existing database>>> conn = psycopg2.connect("dbname=test user=postgres")# Open a cursor to perform database operations>>> cur = conn.cursor()# Execute a command: this creates a new table>>> cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")# Pass data to fill a query placeholders and let Psycopg perform# the correct conversion (no more SQL injections!)>>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",...      (100, "abc'def"))# Query the database and obtain data as Python objects>>> cur.execute("SELECT * FROM test;")>>> cur.fetchone()(1, 100, "abc'def")# Make the changes to the database persistent>>> conn.commit()# Close communication with the database>>> cur.close()>>> conn.close()


0 0
原创粉丝点击