当前位置: 移动技术网 > IT编程>脚本编程>Python > postgresql Python 简单应用

postgresql Python 简单应用

2020年07月30日  | 移动技术网IT编程  | 我要评论
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

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网