Search code examples
pythonmysqlpython-3.xmysql-connector

My program is not being able to store values in MySQL using mysql connector lib in Python


I was building a login/signup program in Python by using MySQL connector lib. My code wasn't able to store values in MySQL. I don't know why it is happening. When i check MySQL, then it says empty set.

Here's my code:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd=""
)

mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE login;")

# sign up
email = input("Your email: ")
passw = input("Your password: ")
confirm_pass = input("Confirm password: ")

if passw == confirm_pass:
    print("Successfuly registered!")

    mycursor.execute("USE login;")
    mycursor.execute("CREATE TABLE id (email VARCHAR(20), passw VARCHAR(20));")

# ----------------------- This is the line ---------------------------#

    mycursor.execute(
        f"INSERT INTO id(email, passw) VALUES({email},{passw});")

# -----------------------                 ---------------------------#

else:
    print("wrong password!")

Any help would be appreciated!


Solution

  • You are doing some dangerous stuff here:

    No String formatting (SQL Injection)

    You shouldn't use String formatting because of SQL Injection. It is also more complicated when you have larger SQL code. Use prepared Statement like:

    query = "INSERT INTO id(email,passw) VALUES(%s,%s)"
    args = (email, passw)
    mycursor.execute(query, args)
    

    Don't create DB/Table new all the time

    Your code is destined to fail everytime because it can't create a new db with the same name if it already exist. The same with table. I would suggest to create a setup script. Also you can put the database in the connector and don't have to use mycursor.execute("USE login;")

    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="",
        database='login'
    )
    

    commit

    mysql connector doesn't autocommit by default see: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-commit.html

    So you have to do it yourself after the execution.

    mydb.commit()
    

    The code should look like this in the end:

    import mysql.connector
    
    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="",
        database='login'
    )
    
    mycursor = mydb.cursor()
    
    # sign up
    email = input("Your email: ")
    passw = input("Your password: ")
    confirm_pass = input("Confirm password: ")
    
    if passw == confirm_pass:
        print("Successfuly registered!")
    
        query = "INSERT INTO id(email,passw) VALUES(%s,%s)"
        args = (email, passw)
        mycursor.execute(query, args)
        mydb.commit()
    
    else:
        print("wrong password!")