python创建postgresql数据库

方式1、

  1. from sqlalchemy import create_engine
  2. from sqlalchemy_utils import database_exists, create_database
  3.  
  4. # postgresql 创建数据库
  5.  
  6. user= data["account"]
  7. pwd = data["pwd"]
  8. host ="w-test.pg.rds.aliyuncs.com"
  9. port = 5432
  10.  
  11.  
  12. url = 'postgresql://{}:{}@{}:{}/{}'
  13. url = url.format(account, pwd, host, port, data["DBName"])
  14.  
  15. engine = create_engine(url)
  16. if not database_exists(engine.url):
  17. create_database(engine.url)
  18.  
  19. print(database_exists(engine.url))

方式2、

  1. import psycopg2
  2. from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
  3.  
  4. user = "haha"
  5. pwd = "123456"
  6. port = 5432
  7. host = "w-test.pg.rds.aliyuncs.com"
  8. db_name = "wahaha"
  9.  
  10. conn = psycopg2.connect(database="postgres", port=port, host=host, user=user, password=pwd)
  11.  
  12. conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
  13.  
  14. cursor = conn.cursor()
  15.  
  16. # 创建数据库
  17. cursor.execute("CREATE DATABASE {}".format(db_name))
  18.  
  19.  
posted @ 2019-08-13 14:34  Awakenedy  阅读(1216)  评论(0)    收藏  举报