Answer the question
In order to leave comments, you need to log in
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()
Answer the question
In order to leave comments, you need to log in
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) # теперь данные в рандомном порядке, можно выбирать последовательно
# считать только уникальные номера этих текстов в список
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 questionAsk a Question
731 491 924 answers to any question