【问题标题】:Why isn't my python program printing my desired results from an sql query?为什么我的 python 程序没有从 sql 查询中打印出我想要的结果?
【发布时间】:2018-12-29 17:08:44
【问题描述】:

我正在使用 IDLE 编写我的 python 程序,并且每当我运行时

python3 [myfilename]

在我的终端中,它没有输出我所做的 SQL 查询应该输出的内容。

我试着看看问题是否出在这 2 行:

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 域套接字上的连接" 有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你检查过你的代码实际上是有效的python语法吗?
  • 是的,它是有效的,因为我通过空闲运行。 import psycopg2 在我的文件顶部
  • 也许我遗漏了一些东西,但是当我尝试运行它时,我得到一个与 c.execute 行相关的语法错误,它看起来像打开然后关闭双引号,然后写查询但不在字符串内。然后在查询结束时打开和关闭双引号。
  • 好的,我已经用引号解决了这个问题。当我运行我的文件时,我得到一个错误是服务器在本地运行并接受 Unix 域套接字上的连接。知道发生了什么吗?
  • 该消息仅供参考 - 这就是 postgres 在本地连接时的工作方式。

标签: python database output database-connection


【解决方案1】:

你需要从你的get_posts 函数中返回一些东西。因为它是您打印 function object 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)

【讨论】:

  • 当我运行我的文件时,我得到一个错误是服务器在本地运行并接受 Unix 域套接字上的连接。知道这是怎么回事吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 2018-10-17
  • 1970-01-01
  • 2021-08-27
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多