Search code examples
pythonselectmysql-connector-python

How to get info from SQL table in python?


I am trying to compare value from SQL database with user discord ID. But my code is printing all IDs from SQL database.

If user's discord ID exist in SQL databse, print values from insert_time, platform, gamertag, kills, downs, kdRatio. If no print error message (you are not registered).

This is my database enter image description here

My code:

print(logTime,">", ctx.author.name,">", "Me command starting here...")
mydb = mysql.connector.connect(
        host = SQL_HOST,
        user = SQL_USER,
        password = SQL_PASSWORD,
        database = SQL_DATABASE
)

sql_select_query_register = f"SELECT * FROM data WHERE discord_id = {ctx.author.id}"
mycursor = mydb.cursor()
mycursor.execute(sql_select_query_register)
records = mycursor.fetchall()
for row in records:
    print(row[0])
    if row[0] == ctx.author.id:
        print(row[1], row[2], row[3], row[4], row[5], row[6])
    else:
        print("you are not registered")

Output:

30.10.2022 14:08:37 > jcK. > Me command starting here...
176432554692313087

you are not registered
176432554692313088
you are not registered

Expecting Output:

30.10.2022 13:34:22 > jcK. > Me command starting here...
176432554692313088
30.10.22 13:14:53, acti, jcK_#2039728, 8840.0, 8672.0, 1.4203084832904884

Solution

  • Your SQL statement will only return rows that contain the user id you are looking for. The code should print the row if any are returned or print "you are not registered" if nothing is found.

    print(logTime,">", ctx.author.name,">", "Me command starting here...")
    mydb = mysql.connector.connect(
            host = SQL_HOST,
            user = SQL_USER,
            password = SQL_PASSWORD,
            database = SQL_DATABASE
    )
    
    sql_select_query_register = f"SELECT * FROM data WHERE discord_id = {ctx.author.id}"
    mycursor = mydb.cursor()
    mycursor.execute(sql_select_query_register)
    records = mycursor.fetchall()
    if records:
        print(records[0])
    else:
        print("you are not registered")