Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python / MySQL – Python INSERT INTO not inserting data

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading