How to count the number of rows in a table in python

1

Example, I have a database called 123, in this database has the players table, which would be where the players' accounts are. I want to count how many accounts there are in the database.

Finally, count the number of rows in a SQLITE3 table, using Python 2.7.

What I have 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.execute ("?")

    
asked by anonymous 12.10.2017 / 03:27

1 answer

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()

Retrieving the 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()
    
12.10.2017 / 03:51