欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

postgresql Python 简单应用

程序员文章站 2022-07-23 11:06:00
postgresql 可以在python下操作次为一些简单操作注意:user passward 要设置正确,不然连不上。端口也要对应好import psycopg2# from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT# conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)user = "postgres"pwd = "123456"port = "5432"hos...

postgresql 可以在python下操作
此为一些简单操作
注意:user passward 要设置正确,不然连不上。
端口也要对应好
(下面程序只连接本机)

import psycopg2

# from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
# conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

user = "postgres"
pwd = "123456"
port = "5432"
host = "127.0.0.1"
# db_name = "wahaha"

conn = psycopg2.connect(database = "komablog", user = user, password = pwd, host = "127.0.0.1", port = port)
cur = conn.cursor()


cur.execute("drop table company;")

cur.execute('''
            create table company
            (ID SERIAL PRIMARY KEY ,
            NAME           TEXT NOT NULL,
            AGE            INT  NOT NULL,
            ADDRESS       CHAR(12),
            SALARY         REAL);
            ''')

cur.execute("insert into company (NAME, AGE, ADDRESS, SALARY) \
            VALUES('Paul', 32, 'California', 20000.00);")

cur.execute("insert into company (NAME, AGE, ADDRESS, SALARY) \
            VALUES('Allen', 25, 'Texas', 15000.00);")


# Get the finding result
cur.execute("select name, ADDRESS,salary from company;")
rows = cur.fetchall()
# rows = cur.fetchone()

for row in rows:
    # print(row)
    print('NAME = {}'.format(row[0]))
    print('ADDRESS = {}'.format(row[1]))
    print('salary = {}'.format(row[2]))

print("------------------------ > - < --------------------------")
print("------------------------ update --------------------------\n")

# Update database
cur.execute("update company set salary = 10000.00 where name = 'Allen'")
cur.execute("select name, ADDRESS,salary from company;")
rows = cur.fetchall()

for row in rows:
    # print(row)
    print('ID = {}'.format(row[0]))
    print('ADDRESS = {}'.format(row[1]))
    print('salary = {}'.format(row[2]))

print("------------------------ > - < --------------------------")
print("------------------- delete one person ---------------------\n")

# delete first people of database
cur.execute("delete from company where name = 'Paul'")
cur.execute("select name, ADDRESS,salary from company;")
rows = cur.fetchall()

for row in rows:
    # print(row)
    print('ID = {}'.format(row[0]))
    print('ADDRESS = {}'.format(row[1]))
    print('salary = {}'.format(row[2]))




conn.commit()
conn.close()

结果如下
postgresql  Python 简单应用

本文地址:https://blog.csdn.net/weixin_39908946/article/details/107658940

相关标签: postgres python