Ubuntu安装postgresql / psycopg2包 / Python连接postgreSQL
Ubuntu 安装 postgresql
命令参考: https://www.postgresql.org/download/
install
# Create the file repository configuration:
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
# Import the repository signing key:
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
# Update the package lists:
sudo apt-get update
# Install the latest version of PostgreSQL.
# If you want a specific version, use 'postgresql-12' or similar instead of 'postgresql':
sudo apt-get install postgresql
进入数据库
su postgres
psql -p 5432
创建用户
该用户名为数据库中的,最好与系统用户名一致
create user lzy with password 'aaa';
创建数据库并赋予权限
CREATE DATABASE dbname OWNER lzy;
CREATE SCHEMA dbschema;
GRANT ALL PRIVILEGES ON DATABASE dbname TO lzy;
GRANT ALL PRIVILEGES ON SCHEMA dbschema TO lzy;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO lzy;
# 超级管理员权限
GRANT postgres TO lzy;
返回自己的系统用户
su lzy
psql -U lzy -d dbaname
重启postgresql
sudo /etc/init.d/postgresql restart
设置搜索表的范围search_path
-- Use this to show the current search_path
-- Should return: "$user",public
SHOW search_path;
-- Create another schema
GRANT ALL ON SCHEMA s1 TO s1;
-- To change search_path on a connection-level
SET search_path TO s1;
-- To change search_path on a database-level
ALTER database "testdb" SET search_path TO s1;
Ubuntu 安装psycopg2包
sudo apt-get install postgresql
sudo apt-get install python-psycopg2
sudo apt-get install libpq-dev
pip3 install psycopg2==2.8.4
Python 使用postgresql连接数据库
import psycopg2
def getConnection():
return psycopg2.connect("dbname='' user='' host='localhost' password='' port='5432'")
conn = getConnection()
cur = conn.cursor()
# 如果新增模式SCHEMA,需要设置搜索路径
cur.execute("""SET search_path TO schema_name""")
# 查询
cur.execute("""select * from table_name""")
data_all = cur.fetchall()