关于Python及pycharm的安装参考:1. python+pycharm 安装及测试_Hehuyi_In的博客-CSDN博客_pycharm安装成功测试
首先需要安装 psycopg2模块(已经有了3版本,不过看网上例子基本还是用2)
pip install psycopg2
下面来看一个例子,执行建表、insert、select操作
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#@Time : 2022/5/21 23:20
#@Author: Hehuyi_In
#@File : pg_test.py
import psycopg2
conn = psycopg2.connect(database="postgres", user="postgres", password="xxxxxxx", host="127.0.0.1", port="5432")
print ("Opened database successfully")
cur = conn.cursor()
cur.execute('''CREATE TABLE t1 (a int,b int);''')
print ("Table created successfully")
cur.execute("INSERT INTO t1 VALUES (1,1)")
cur.execute("INSERT INTO t1 VALUES (2,2)")
print ("Table inserted successfully")
cur.execute("SELECT a,b from t1")
rows = cur.fetchall()
for row in rows:
print ("a = ", row[0])
print ("b = ", row[1])
conn.commit()
conn.close()
执行结果
我们在pg中再查一下
参考