postgresql_python编程

1.前提:

依赖sycopg2模块(PostgreSQL数据库适配器,小巧、快速、稳定);

linux安装:

#安装
yum install python-psycopg2

windows安装:

#升级pip
pip install -U pip
#安装psycopg2
pip install psycopg2

失败的情况,下载安装包,地址:

https://github.com/psycopg/psycopg2/releases/

现在的zip包解压以后,按照readme安装提示缺少依赖。

 

通过https://github.com/psycopg/psycopg2/tree/new-release-procedure提示,安装,成功。

pip install psycopg2-binary

2.使用:

(1)连接

import psycopg2

conn = psycopg2.connect(database="db名", user="user名", password="密码", host="ip地址", port="5432")

(2)操作

连接后,返回游标;

游标具有execute('sql语句')方法,可以执行sql语句;

游标具有fetchall()方法,可以返回查询结果;

cur = conn.cursor()
#建表
cur.execute('''CREATE TABLE table名 (字段、类型、属性);''')
conn.commit()

#增加数据
cur.execute("INSERT INTO table名(字段1,字段2...) VALUES (值1, 值2... )");
conn.commit()

#删除数据
cur.execute("DELETE from table名 where 字段 = 值;")
conn.commit()

#改变数据
cur.execute("UPDATE table名 set 字段 = 值 where 字段 = 值;")
conn.commit()

#查找数据
cur.execute("SELECT 字段1,字段2 from table名")
##输出查询结果
rows = cur.fetchall()
for row in rows:
    print row[0],row[1]...

conn.close()

 

你可能感兴趣的:(postgresql)