对本文有疑问可以加微信 Tutor_0914联系。也可查看个人辅导网站了解详情:
tutoryou辅导详情
文章目录- 安装postgresql
- 安装psycopg2
- 加载数据库与sql
- # could not change directory to "/home/ubuntu": Permission denied
- 也可以进入到postgres这个用户的命令行
- 和python的交互
- 基本设置
- Python代码执行并运行
三条指令,傻瓜式安装
安装psycopg2必须先有postgresql,才能安装这个指令
加载数据库与sql # could not change directory to “/home/ubuntu”: Permission denied会报错,但不影响。
在腾讯云的正常ubuntu界面下:
sudo -u postgres dropdb imdb # 删除数据库 sudo -u postgres createdb imdb #创建数据库 bzcat imdb.dump.bz2 | sudo -u postgres psql imdb # 加载想要的数据 sudo -u postgres psql imdb # 大概某数据库的交互式界面,命令行使用 q退出 #sudo -u postgres psql imdb -f ass1.sql # 使用-f,无法加载sql文件 sudo -u postgres psql imdb < ass1.sql # 使用重定向加载sql文件
可以通过加载sql,以及在交互式命令行写sql的方式使用起来。
也可以进入到postgres这个用户的命令行# 法2 进命令行再操作。 sudo -i -u postgres createdb imdb和python的交互 基本设置
一开始会提示:psql: error: FATAL: Peer authentication failed for user “postgres”
权限不够:
修改这个文件里的权限,把peer改成了trust,trust > peer > md5, trust最松
sudo vim /etc/postgresql/12/main/pg_hba.conf
# Database administrative login by Unix domain socket local all postgres trust # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. local replication all peer host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5
如果还不行,看看这两个链接:可以不用密码登录
https://gabrielinnocentrockerfeller.medium.com/how-to-fix-fatal-password-authentication-failed-for-user-postgres-in-ubuntu-20-4-f7c6d2856fc9
https://stackoverflow.com/questions/21483540/postgres-password-authentication-issue
Python代码执行并运行import sys
import psycopg2
try:
hostname = 'localhost'
port_id = 5432
db = psycopg2.connect(database="imdb",
user="postgres",
password="postgres",
host = hostname,
port = port_id ) # postgres
# db = psycopg2.connect("dbname=imdb")
# ... add your code here ...
cur = db.cursor()
cur.execute(query)
tables = cur.fetchall()
except psycopg2.Error as err:
print("DB error: ", err)
finally:
if db:
db.close()
# print(type(tables))



