Read data from an Sqlite 3 database in Python

Asked

Viewed 1,720 times

0

I’m starting in Python and database and I have three questions!

  1. For example, inside my database I have a "name" column. Just to illustrate, say I want to take the contents of the "name" column corresponding to id= 1 and play in a Python variable called "client name"?

  2. How do I list the total number of existing records?

  3. If I want to make a button in Python that navigates between records How should it be done? It has something like cursor.next and cursor.Previous, for example?

Thank you very much, guys!

1 answer

0

I did this way, I believe it is the simplest, uses more Python code than SQL resources.

import sqlite3

conn = sqlite3.connect("teste.db")
cursor = conn.cursor()

cursor.execute("create table if not exists testes ( nome varchar(50));")

for i in range(1, 1001):
    cursor.execute("insert into testes values (' testando like a boss %s')" %i)

cursor.execute("select * from testes")

count = 0

for row in cursor.fetchall():
    print(row)
    count += 1
    if (count % 10) == 0:
        escolha = input('c - continuar, p - parar? \n')
        if escolha.lower() == 'c':
            pass
        elif escolha.lower() == 'p':
            break
conn.commit()

conn.close()

I hope it helps.

  • Hello @Fonso.Prog ! Beauty? Face, at the end I got it like this: #move to the last registered record: cursor.execute("SELECT idClient FROM clients ORDER BY idCliente desc limit 1") #plays for a variable in python and removes the quotes and parentheses: codClient = " ". Join(map(str, cursor.fetchone()) #assign to the textfields of the program the value of the stored variable self.ids.tf_codCliente.text = codCliente But thank you very much for the idea, also very good!!

Browser other questions tagged

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