Python / MySQL – Python INSERT INTO not inserting data

Question:

I’m testing a combination with Python and MySQL. For this example I want to insert data into a MySQL Database from my Python code. The problem I’m facing now is that there is no actual data inserted into the table when I run the SQL command via Python, but it works when I run it via the MySQL Command Line Client.

The DB name is sha.

The table was created as follows:

CREATE TABLE sha_data (string varchar(255), sha256 char(64))

The Python code looks like this:

import mysql.connector


def sql_run_command(sql, val):
    try:
        cursor.execute(sql, val)
        result = cursor.fetchall()

    except Exception as e:
        print(f'Error on SQL command | {sql} | {e}')

    return result

# Database connect
db = mysql.connector.connect(
            host="localhost",
            user="root",
            password="1234",
            database="sha"
        )

# Cursor creation
cursor = db.cursor()

# Command & variables
sql = "INSERT INTO sha_data (string, sha256) VALUES (%s, %s)"
val = ("1", "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b")
print(sql_run_command(sql, val))

# Connection close
db.close()

If I run this code the return is [], and if I check it with SELECT * FROM sha_data there is no data.

I’m not quite sure where the problem is sitting. I would guess it’s a simple syntax error.

Asked By: LiiVion

||

Answers:

you forgot to commit your changes, add this line

db.commit()

after executing the sql query, make sure to pass the db to the sql_run_command method, here’s an example from the documentation
Inserting Data Using Connector/Python

Answered By: Amr Alaa
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.