PostgreSQL安装教程(Win10)
pip install psycopg2 -i https://pypi.tuna.tsinghua.edu.cn/simple
# coding=utf-8
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()
# create_table(cursor)
# insert_operate(cursor)
# TODO: update操作(必须commit)
cursor.execute("update public.member set name='update1 ...' where id=2")
connect.commit()
print "Total number of rows updated :", cursor.rowcount # 更新的行总数
# TODO: Select操作(不用commit)
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") # 查询public.member表的所有行
rows = cursor.fetchall()
for row in rows:
print 'id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], '\n'
# TODO: Delete操作
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()