使用Psycopg2从Jupyter Notebook连接PostgreSQL数据库失败求助
问题:Jupyter Notebook连接PostgreSQL时出现"role不存在"错误
尝试从Jupyter Notebook连接PostgreSQL数据库并向表中插入数据,使用代码如下:
# connect to the database #url = postgresql+psycopg2://postgres@localhost:5432/citibike' from sqlalchemy import create_engine engine = create_engine('postgresql://localhost/citibike') con = engine.connect() df_date.to_sql('date_dim', con, if_exists='append',index=False,chunksize=10000) stations.to_sql('stations', con, if_exists='append',index=False,chunksize=10000) trip_demo.to_sql('trip_demo', con, if_exists='append',index=False,chunksize=10000) df_weather.to_sql('weather', con, if_exists='append',index=False,chunksize=10000) rides.to_sql('rides', con, if_exists='append',index=False,chunksize=10000) con.close()
运行代码时出现错误:
OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: FATAL: role "rkb18" does not exist
注:rkb18是Windows系统用户名,已确认主机、数据库、端口等信息正确,使用Postbird作为PostgreSQL操作界面。
解决建议
原因
PostgreSQL在连接字符串未指定用户名时,会默认使用当前操作系统的用户名(即rkb18)尝试登录,但你的PostgreSQL实例中没有创建这个角色,因此报错。
方法1:在连接URL中明确指定合法的PostgreSQL用户名
修改create_engine的连接字符串,添加你Postbird使用的用户名(通常默认是postgres):
# 无密码时的格式 engine = create_engine('postgresql://postgres@localhost/citibike') # 若PostgreSQL设置了密码,格式如下 engine = create_engine('postgresql://postgres:你的数据库密码@localhost/citibike')
方法2:在PostgreSQL中创建对应操作系统用户名的角色
打开Postbird连接到数据库,执行以下SQL命令创建角色并赋予权限:
-- 创建角色并允许登录 CREATE ROLE rkb18 WITH LOGIN; -- 给角色赋予citibike数据库的全部权限 GRANT ALL PRIVILEGES ON DATABASE citibike TO rkb18;
修改后重新运行Jupyter中的代码即可正常连接并插入数据。
内容的提问来源于stack exchange,提问作者Ray B
相关产品推荐
相关产品推荐

