1 PostgreSQL安装
PostgreSQL安装教程(Win10)
2 安装psycopg2
pip install psycopg2 -i https://pypi.tuna.tsinghua.edu.cn/simple
3 Python 交互 PostgreSQL 数据库 demo
import os
import sys
import psycopg2
def connect_postgreSQL():
conn = psycopg2.connect(database="postgres", user="postgres", password="12345", host="localhost", port="5432")
cur = conn.cursor()
print 'connect successful!'
return conn, cur
def create_table(cur):
cur.execute('''create table public.member(id integer not null primary key,
name varchar(32) not null,
password varchar(32) not null,
singal varchar(128))''')
print 'table public.member is created!'
def insert_operate(cur):
cur.execute("insert into public.member(id,name,password,singal) values(1,'member0','password0','signal0')")
cur.execute("insert into public.member(id,name,password,singal) values(2,'member1','password1','signal1')")
cur.execute("insert into public.member(id,name,password,singal) values(3,'member2','password2','signal2')")
cur.execute("insert into public.member(id,name,password,singal) values(4,'member3','password3','signal3')")
print 'insert records into public.memmber successfully'
if __name__ == '__main__':
connect, cursor = connect_postgreSQL()
cursor.execute("update public.member set name='update1 ...' where id=2")
connect.commit()
print "Total number of rows updated :", cursor.rowcount
cursor.execute("select id,name,password,singal from public.member where id>2")
rows = cursor.fetchall()
for row in rows:
print 'id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], '\n'
cursor.execute("select * from public.member")
rows = cursor.fetchall()
for row in rows:
print 'id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], '\n'
print 'begin delete'
cursor.execute("delete from public.member where id=2")
connect.commit()
print 'end delete'
print "Total number of rows deleted :", cursor.rowcount
cursor.execute("select * from public.member")
rows = cursor.fetchall()
for row in rows:
print 'id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], '\n'
connect.close()