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

Mel*_*nie 7 python postgresql pyodbc

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

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

查询是

select id from a_company where name = 'somename'
Run Code Online (Sandbox Code Playgroud)

结果

7
8
9
Run Code Online (Sandbox Code Playgroud)

等(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()
Run Code Online (Sandbox Code Playgroud)

通过pyodbc的调用返回

None
Run Code Online (Sandbox Code Playgroud)

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

我最好的猜测是这是一个权限问题,而且我已经用这个特定的表做了一些蠢事.

任何人都可以建议如何调试这个?

通过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");
Run Code Online (Sandbox Code Playgroud)

如果我修改它只是为了更改表名,那么我得到另一个"正常"工作的表.但是我将id行更改为id serial而不是指定序列.

小智 0

你可以尝试这样的事情:

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'])

Run Code Online (Sandbox Code Playgroud)