How to count the number of "Rows" in a python table

Asked

Viewed 1,978 times

1

For example, I have a database called 123, in this database is the players table, which is where the players' accounts are. I want to count how many accounts there are in the database.

Finally, count the number of Rows from an SQLITE3 table, using PYTHON 2.7.

What I got so far:

# -*- coding: cp1252 -*-
import sqlite3

# Connexion for database
try:
    print "Tentando conectar-se ao banco de dados."
    Database, Cursor = None, None
    Database = sqlite3.connect("./database/database.db", check_same_thread = False)
    Database.text_factory = str
    Database.isolation_level = None
    Database.row_factory = sqlite3.Row
    Cursor = Database.cursor()
    print "Conectado com o banco de dados.\n"
except:
    print "[ERROR] Falha na conexão do banco de dados."

Cursor.("?")

  • Okay, what do you already have of code so far? Have you managed to connect to the database with Python? Gave any error? You know SQL?

  • Att: Codico att I have connection, no errors in connection. =/

  • What about SQL? You know how a query is made with SQL?

  • I know very little about SQL, more know yes Delete, update, insert values in tables. Query also.

  • Try to run the query: select count(*) from jogadores

2 answers

2


Creating database containing a player table with 3 records:

import sqlite3

jogadores = [ { "id" : 1, "nome" : "Joao" }, { "id" : 2, "nome" : "Maria" }, { "id" : 3, "nome" : "Jesus" } ]

conn = sqlite3.connect('foobar.db')

c = conn.cursor()

c.execute("CREATE TABLE tb_jogador ( id integer, nome text );")

for j in jogadores:
    c.execute("INSERT INTO tb_jogador ( id, nome ) VALUES ( %d, '%s' );" % ( j["id"], j["nome"] ))

conn.commit()
conn.close()

Recovering amount of records contained in the table:

import sqlite3

conn = sqlite3.connect('foobar.db')

c = conn.cursor()

c.execute('SELECT count(1) FROM tb_jogador')

count = list(c)[0]

print("Quantidade de jogadores registrados: %d" % (count) )

conn.close()

1

You could do that too:

cursor.execute(f'SELECT * FROM jogadores')
count = len(cursor.fetchall())

fetchall() takes all the rows of your table and puts them in a tuple, all of them within a list. So just put Len to count how many values are inside that list. :)

website: https://pynative.com/python-cursor-fetchall-fetchmany-fetchone-to-read-rows-from-table/

cursor.fetchall(): searches all rows of a query result. It returns all rows as a list of tuples. An empty list is returned if there is no record to search.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.