gpt4 book ai didi

python - 无法通过 pyodbc 从 postgresql 数据库上的一个表中进行选择 - 如何调试

转载 作者:行者123 更新时间:2023-11-29 11:22:37 24 4
gpt4 key购买 nike

我有一个 postgresql 数据库,其中包含一些由 drupal 创建的表,以及我自己创建的其他表。然后我有一个 python api,使用 pyodbc,来查询数据库。

只有一张表,我无法通过 pyodbc 从中选择。如果我打印查询并将其粘贴到 pgadminIII,那么它会给出预期的结果,如果我在 python 代码中更改表,它会给出正确的结果。

查询是

select id from a_company where name = 'somename'

结果

7
8
9

等(50 行 int id)

我的python代码是

sql = """select id from a_company where name = 'somename'"""
curs = self._connection.cursor()
sql = self._ConvertToPostGres(sql) #drops [] etc, as the initial code was for MSSQL
curs.execute(sql)
f = curs.fetchall()

通过pyodbc 调用返回

None

(我可以使用相同的连接从其他表中进行选择,所以连接字符串无关紧要?)

我最好的猜测是这是一个权限问题,我对这个特定的表做了一些愚蠢的事情。

谁能建议如何调试它?

通过 pgadmin 创建表:

-- Table: a_company

-- DROP TABLE a_company;

CREATE TABLE a_company
(
id integer NOT NULL DEFAULT nextval('a_company_id_seq'::regclass),
name character varying,
abn character varying,
url character varying,
anzsic character varying(5),
address character varying,
area integer,
sell_equipment boolean,
recycling_provider boolean,
monthly_matches boolean,
user_id bigint,
latitude double precision,
longitude double precision,
geography geography,
CONSTRAINT a_company_pkey PRIMARY KEY (id),
CONSTRAINT fk_a_company_a_anzsic_codes FOREIGN KEY (anzsic)
REFERENCES a_anzsic_codes (code) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE a_company
OWNER TO aspire;

-- Index: fki_a_company_aspire_a_codes

-- DROP INDEX fki_a_company_aspire_a_codes;

CREATE INDEX fki_a_company_aspire_a_codes
ON a_company
USING btree
(anzsic COLLATE pg_catalog."default");

如果我修改它足以更改表名,那么我会得到另一个可以正常“工作”的表。但是我将 id 行更改为只是 id serial 而不是指定序列。

最佳答案

你可以尝试这样的事情:

def load_data(sql, columns):
sql_data = []

curs = self._connection.cursor()
sql = self._ConvertToPostGres(sql)

try:
curs.execute(sql)
rows = curs.fetchall()
pass
except Exception as e:
print(e)
rows = pd.read_sql(sql, self._connection)

for row in rows:
sql_data.append(list(row))

df = pd.DataFrame(data=sql_data, columns=columns)

return df


sql = "select id from a_company where name = '{0}'".format(somename)
data = load_data(sql, ['id'])

关于python - 无法通过 pyodbc 从 postgresql 数据库上的一个表中进行选择 - 如何调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28672295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com