为什么我的python程序无法从sql查询中打印所需的结果?

时间:2018-12-29 17:08:45

标签: python database output database-connection

每当我运行时,我都会使用IDLE编写python程序

python3 [myfilename]

在我的终端中,它不会输出应该从我进行的SQL查询中输出的内容。

我尝试查看问题是否出在这两行上:

c = db.cursor()
c.execute("select content time from posts order by time desc")

并猜测可能

db.cursor() = c
db.cursor(execute("select * from posts))
posts = db.fetchall()

print(add_post());

实际上会添加一些东西,但是我没有输出!基本上,我希望它能打印出数据库中的任何内容。

def get_posts():
    db = psycopg2.connect(database="forum")
    c = db.cursor()
    c.execute("select content, time from posts order by time desc")
    posts = c.fetchall()
    db.close()

get_posts()
print(get_posts)

我希望我的输出可以在终端中打印任何数据,但是运行文件实际上并不会打印任何内容。请帮忙!


编辑:我在IDLE中的新错误是“服务器是否在本地运行并接受     Unix域套接字上的连接” 有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您需要从get_posts函数返回一些信息。在您打印函数 对象 get_posts时,其外观类似于<function get_post at 0x7f42d60bcf28>

您应该看起来像这样:

def get_posts():
    db = psycopg2.connect(database="forum")
    c = db.cursor()
    c.execute("""select content, time from posts order by time desc""")
    posts = c.fetchall()
    db.close()
    # Return a value
    return posts

# Call the function and assign the return value to a variable
the_posts = get_posts()
# Print the variable
print(the_posts)
相关问题