Create Random User with MySQL Database

  • Share this:

Code introduction


This function connects to a MySQL database, creates a new user named 'random_user', generates a random 10-character password for this user, and then inserts the username and password into the 'users' table in the database.


Technology Stack : python, mysql-connector-python

Code Type : Function

Code Difficulty : Intermediate


                
                    
def get_random_user_password():
    import random
    import string
    from mysql.connector import connect, Error

    # Connect to the MySQL database
    try:
        connection = connect(
            host='localhost',
            user='your_username',
            password='your_password',
            database='your_database'
        )
        cursor = connection.cursor()

        # Generate a random password
        chars = string.ascii_letters + string.digits
        password = ''.join(random.choice(chars) for _ in range(10))

        # Insert the new user with the random password into the database
        query = "INSERT INTO users (username, password) VALUES (%s, %s)"
        values = ('random_user', password)
        cursor.execute(query, values)
        connection.commit()

        print(f"User 'random_user' created with password: {password}")

    except Error as e:
        print(f"Error: {e}")

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()