Python操作PostgreSQL数据库

来源:互联网 发布:蒙特卡洛随机算法模型 编辑:程序博客网 时间:2024/05/16 14:53

1.简述

python可以操作多种数据库,诸如SQLite、MySql、PostgreSQL等,而本文仅针对PostgreSQL做一下简单介绍,主要包括python操作数据库插件的选择、安装、简单使用方法、测试连接数据库成功。

2.数据库插件选择

  PostgreSQL至少有三个python接口程序可以实现访问,包括PsyCopg、PyPgSQL、PyGreSQL(PoPy已经整合在PyGreSQL中),三个接口程序各有利弊,需要根据实践选择最适合项目的方式。推荐使用PsyCopg,对python开发框架的兼容性都很好,本文中我们只讨论这个插件。

3.PsyCopg的下载

  本文使用windows系统开发,未使用官网版本,选择psycopg2-2.4.2.win-amd64-py2.7-pg9.0.4-release.exe版,地址:http://vdisk.weibo.com/s/Cd8pPaw56Ozys

4.PsyCopg的安装

  直接exe,根据提示安装即可.

5.PsyCopg的使用

# __author__ = 'ETwise'import psycopg2# set connect parameterconn=psycopg2.connect(database="test",user="postgres",password="postgres",host="localhost",port="5432")cur=conn.cursor()# create one tablecur.execute("CREATE TABLE student(id integer,name varchar,sex varchar);")# insert one itemcur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)",(1,'TONY','M'))cur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)",(2,'Michelle','F'))cur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)",(3,'Albert','M'))# get resultcur.execute('SELECT * FROM student')results=cur.fetchall()print results# close connectconn.commit()cur.close()conn.close()

6.返回结果

E:\Python27\python.exe E:/Python工具存放/Python课程学习资料/python操作PostgreSQL.py[(1, 'TONY', 'M'), (2, 'Michelle', 'F'), (3, 'Albert', 'M')]Process finished with exit code 0


整个过程如下:

1.import psycopg2

python> import psycopg2

2.创建连接对象

python> conn=psycopg2.connect(host="hostname",user="username",passwd="password",db="database_name")

3.创建指针对象

python> cur=conn.cursor()

4.执行语句

python> cur.execute('select cloumn_name from table_name where contions')

5.获取结果

python> results=cur.fetchall()

python> print results

fetchall方法返回的结果是一串tuples(元组),对元组进行处理,得到一定格式的输出。

6.关闭连接

python> conn.commit()

python> cur.close()

python> conn.close()



0 0
原创粉丝点击