使用Python(第三方包psycopg2)交互PostgreSQL数据库

1 PostgreSQL安装

PostgreSQL安装教程(Win10)

2 安装psycopg2

pip install psycopg2 -i https://pypi.tuna.tsinghua.edu.cn/simple

3 Python 交互 PostgreSQL 数据库 demo

# 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值