S
S
Sergey Kolesnik2021-07-18 09:50:23
Python
Sergey Kolesnik, 2021-07-18 09:50:23

How to output one specific row from the database?

Good time of the day. I am writing a program that will tell jokes (in the future about the events of a particular day, well, the essence is not important). For example, if the user selects the button (or item in the input) "joke", then one of the hundred jokes should randomly get out and display it. That is, the user has chosen "> 2 get" , he should get a joke randomly, when he presses again (selecting the number 2), a joke should fall out again but a different one. I'm not a programmer myself, I'm just learning, for specialists who think a lot here, it will not be difficult to share advice.

import sqlite3 as sql
import sqlite3

import random

while True:
    def menu():
        
        print("1 - добавление\n2 - получение\n3 - вывести всё")
        choice = int(input("> "))
        con = sql.connect('test1.db')
        with con:
            cur = con.cursor()
            cur.execute("CREATE TABLE IF NOT EXISTS 'test' ('number' INT, 'name' STRING)")
    
            if choice == 1:
                
                number = (int(input ('Press number   ')))
                name = input("Name\n> ")
                
                cur.execute(f"INSERT INTO 'test' VALUES ('{number}','{name}')")
            elif choice == 2:
                
                #c = [random.randint(1,4) for c in range(1)]
                

                c = random.randint(1,4)
                
                print (c)
                cur.execute("SELECT *  FROM  `test` WHERE   number")
                
                rows = cur.fetchmany(c)
                
                for row in rows:
                    
                    
                    print(row[1])



            elif choice == 3:
                cur.execute("SELECT * FROM `test`")
                rows = cur.fetchall()
                
                for row in rows:
                    print(row[0], row[1])
                    
            
               
            else:
                print("Вы ошиблись")

            con.commit()
            cur.close()
            
    menu()


with the cur.fetchall() command, everything is displayed as it should, but here's how to make the program output cur.fetchone() only from a certain one that will give out variable C. I've already searched the entire Internet (((

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2021-07-18
@o5a

With this setting, it would be optimal to select all the values ​​from the base into the list (once, without sorting), and then shuffle it and return the next value in the list with each request.

# считать все свои тексты в список
data = [row[0] for row in cur.execute("SELECT name FROM `test`")]
random.shuffle(data) # теперь данные в рандомном порядке, можно выбирать последовательно

An alternative option (for example, there is a lot of this textual data in the table and it may not be efficient to pull and store them all at once), read the list of numbers, also sort it, and with each user request, make a request to the database already by number.
# считать только уникальные номера этих текстов в список
numbers = [row[0] for row in cur.execute("SELECT number FROM `test`")]
random.shuffle(numbers) # теперь данные в рандомном порядке, можно выбирать последовательно

# при запросе пользователя берем следующий номер из нашего рандомного списка
number = ...
# и по нему уже достаем сам текст из базы
text = cur.execute("SELECT name FROM `test` where number = ?", (number, )).fetchone()[0]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question