postgresql 获取psycopg2 count(*)结果数

qmelpv7a  于 12个月前  发布在  PostgreSQL
关注(0)|答案(3)|浏览(92)

获取此查询返回的行数的正确方法是什么?我特别想看看是否没有返回结果。

sql = 'SELECT count(*) from table WHERE guid = %s;'
data=[guid]
cur.execute(sql,data)
results = cur.fetchone()
for r in results:
  print type(r) # Returns as string {'count': 0L} Or {'count': 1L}
ct2axkht

ct2axkht1#

results本身是一个行对象,在您的例子中(根据print输出判断),是一个字典(您可能配置了一个类似于dict的游标子类);只需访问count键:

result = cur.fetchone()
print result['count']

因为使用了.fetchone(),所以只返回一行,而不是一个行列表。
如果你 not 使用dict(-like)行游标,行是元组,count值是第一个值:

result = cur.fetchone()
print result[0]
erhoui1w

erhoui1w2#

这可能对那些遇到这个线程的人有帮助,这里是一种使用Python计算数据库中每个表的所有行的方法:

total_count = 0

with con.cursor() as cur:
    cur.execute("""SELECT table_name FROM information_schema.tables
           WHERE table_schema = 'public'""")

    for table in cur.fetchall():
        table_name = table[0]
        cur.execute(sql.SQL("SELECT COUNT(*) FROM {table}").format(table=sql.Identifier(table_name)))
        table_count = cur.fetchone()
        result = f'TABLE NAME: {table_name}, COUNT: {table_count}'
        total_count += int(table_count[0])
        print(result)

print(total_count)
dzhpxtsq

dzhpxtsq3#

以下为我工作

cur.execute('select * from table where guid = %s;',[guid])
rows = cur.fetchall()
print 'ResultCount = %d' % len(rows)

**缺点:如果你需要的只是计数,那么这对DBMS来说不是很有效。

相关问题