是否有一种方法可以像在Hibernate中那样使用asyncpg在PostgreSQL服务器中创建数据库,
jdbc:mysql://localhost:3306/db_name?createDatabaseIfNotExist=true
uri中的标志。有没有一种方法可以连接到服务器而不连接到数据库并执行sql语句?
答案 0 :(得分:0)
在asyncpg中没有实现此目的的捷径,但是在您的代码中很容易实现。每个PostgreSQL集群都有一个CREATE DATABASE
数据库,如果您要连接的原始数据库不存在,则可以使用该数据库发出CREATE DATABASE
语句。 template1
通常需要特殊特权,因此在连接到postgres
(通常为import asyncio
import asyncpg
async def connect_create_if_not_exists(user, database):
try:
conn = await asyncpg.connect(user=user, database=database)
except asyncpg.InvalidCatalogNameError:
# Database does not exist, create it.
sys_conn = await asyncpg.connect(
database='template1',
user='postgres'
)
await sys_conn.execute(
f'CREATE DATABASE "{database}" OWNER "{user}"'
)
await sys_conn.close()
# Connect to the newly created database.
conn = await asyncpg.connect(user=user, database=database)
return conn
asyncio.get_event_loop().run_until_complete(
connect_create_if_not_exists(user='elvis', database='new-database')
)
)时,您需要使用超级用户帐户。
示例:
my_list[0]
March,'1.800931853','1.843227636','1.861992226','1.880196477','1.907555762','1.853076585','1.770560438','1.837108443','1.867213313','1.849542335','1.913505573','2.023772836','1.899717681'
my_list[1]
July,'10.809832','10.57868801','9.571741038','8.850265221','9.154250034','9.172628705','10.35004201','9.36852657','8.689944331','10.1053826','9.18756731','8.541507801','8.054240996'