python - 连接数据库时出错

标签 python linux psycopg2

我无法使用 psycopg2 连接到 Linux 中的数据库。我在 Linux 中安装了 postgresql,我的代码是:

import psycopg2

def testEgg():

    conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")

    cur = conn.cursor()
    cur.execute("CREATE TABLE egg ( num integer, data varchar);")
    cur.execute("INSERT INTO egg values ( 1, 'A');")
    conn.commit()

    cur.execute("SELECT num from egg;")
    row = cur.fetchone()

    print row

    cur.close()
    conn.close()

testEgg()   

我收到错误:

psycopg2.OperationalError: FATAL:  Ident authentication failed for user "postgres"

此代码在 windows7 中运行良好,但在 linux 中出现上述错误。 linux 还有什么需要我做的吗?任何建议将不胜感激。 谢谢。

最佳答案

这不是您的代码的问题,而是由于 postgres 用户的许可造成的问题。

您应该创建一个新用户来访问您的数据库并替换它:

conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")

by(将 <your_user> 替换为您的真实用户名...)

conn = psycopg2.connect("dbname = myDatabase user = <your_user> port = 5432")

要在 postgres 上创建新用户,您可以使用“createuser”二进制文件。该文档可用 here .

关于python - 连接数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963739/

相关文章:

python - 创建具有任意开始日期的每月时间序列

javascript - Python NetworkX/Mplleaflet : network to geojson

python - 如何在 sqlalchemy 中将列名和表名呈现为带引号的字符串?

linux - Bash:返回值不完整

linux - 用/在搜索字符串中替换 bash 文件中的文本

python - Postgresql 如何使用 CSV COPY TO STDIN 进行冲突更新?

python - 我希望一个函数能够将字符串列表或多个字符串作为参数作为 *args

linux - 如何避免在 Raspbian 的 xrdp 下对某些程序使用 sudo?

python - 将 psycopg2 DictRow 查询转换为 Pandas 数据框

python - 比较python中的日期