[Python] How to generate a random number but it should NOT exist in table? [closed]

Discussão em 'Python' iniciado por Stack, Setembro 27, 2024.

  1. Stack

    Stack Membro Participativo

    I need help in creating a code for my own project. It is like a registration site replica but in Python and MySQL.

    I need to generate a random number and check if it already exist in table and if it exist generate another number that should also not exist in table.

    I have made a code which I think is pretty basic and wrong but a little helpful and I need a code like this only.

    import random
    import mysql.connector

    db = mysql.connector.connect(host="", user="", password="")
    cur = db.cursor()

    cur.execute("USE iscr")
    r = random.randint(1,20)
    print(r)
    i = str(r)
    cur.execute("SELECT sno FROM schedule")
    x = str(cur.fetchall())
    while i in x:
    if i in x:
    r = random.randint(1,20)
    print(r)
    else:
    print(r)
    break

    Continue reading...

Compartilhe esta Página