通过 Psycopg 插入到 Pg

发布于 2024-08-12 06:11:49 字数 668 浏览 13 评论 0 原文

如何修复 Python 中的 SQL 语句?

数据库连接有效。但是,cur.execute 返回 none,这是错误的。

我的代码

import os, pg, sys, re, psycopg2

try:
   conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'")
except: print "unable to connect to db"
cur = conn.cursor()

print cur.execute("SELECT * FROM courses")     # problem here

Psql 中的 SQL 命令返回正确的输出。 我可以类似地在 Psql 中运行 INSERT,但不能通过 Python 脚本运行。 我没有收到 /var/log 的警告/错误。

可能的错误是

  1. cursor(),似乎是正确的
  2. 方法的语法connect(),但是似乎没问题

How can you fix the SQL-statement in Python?

The db connection works. However, cur.execute returns none which is false.

My code

import os, pg, sys, re, psycopg2

try:
   conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'")
except: print "unable to connect to db"
cur = conn.cursor()

print cur.execute("SELECT * FROM courses")     # problem here

The SQL-command in Psql returns me the correct output.
I can similarly run INSERT in Psql, but not by Python's scripts.
I get no warning/error to /var/log.

Possible bugs are

  1. cursor(), seems to be right however
  2. the syntax of the method connect(), seems to be ok however

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

私藏温柔 2024-08-19 06:11:49

您必须调用 cur 上的 fetch 方法之一(fetchone、fetchmany、fetchall)才能实际获取查询结果。

您可能应该阅读 教程 for DB-API

You have to call one of the fetch methods on cur (fetchone, fetchmany, fetchall) to actually get the results of the query.

You should probably have a read through the a tutorial for DB-API.

动听の歌 2024-08-19 06:11:49

您必须调用 cur.fetchall() 方法(或其他 fetch*() 方法之一)才能从查询中获取结果。

You have to call cur.fetchall() method (or one of other fetch*() methods) to get results from query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文