SQL: Executed query through python doesn't work but executing the exact query from cmd works

I’m learning SQL and wanted to create a database of username and passwords as a practice.
This is my code:

import mysql.connector
import re

cnx = mysql.connector.connect(
    user="root", password="123", host="", database="db2"
cursor = cnx.cursor()

    query = "CREATE TABLE userpass (Username varchar(320), Password varchar(320));"

regex = re.compile(r"([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+")
user_email = input("Enter your username")
while re.fullmatch(regex, user_email) == None:
    user_email = input(
        "Your username should be in the from of expression@string.string"

user_pass = input("Enter your password")
query = "INSERT INTO userpass VALUES ('{}', '{}');".format(user_email,user_pass)


When I run it, it creates the table so I know that I’m connected to the database but the second query doesn’t do anything.
Weirdly, when I copy the printed query (below) in the cmd it works and adds the values to the table.

INSERT INTO userpass VALUES ('ASD@ADS.com', 'ASDlk');

I don’t understand where the problem is, and it doesn’t return any error.

>Solution :

You aren’t explicitly committing your connection, so it’s implicitly rolled back when the connection is closed. The table will stay there since it creating is a DDL statement, but the inserted data will be lost. Add a call to commit before closing the connection and you should be OK:


Leave a Reply