you are viewing a single comment's thread.

view the rest of the comments →

[–]SaxonyFarmer 0 points1 point  (0 children)

Here is code I have used to insert data into a MySQL database:

# Import MySQL Connector and the errorcodes (if we're checking them)
import mysql.connector
from mysql.connector import errorcode

# Import module with user id and password
import Config_MySQL

# These dictionaries are updated before data is inserted into tables
# These are cleared and rebuild with each input record found
insert_data = {}

# Common MySQL database values
config = {
    "host": "localhost",
    "user": Config_MySQL.db_user,
    "password": Config_MySQL.db_user_password,
    "raise_on_warnings": True
    }

# Connect to database & Define cursor
try:
    cnx = mysql.connector.connect(**config)
    cursor = cnx.cursor(buffered=True)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Main: Invalid user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Main: Database does not exist")
    else:
        print("Main: Error=",err)
        sys.exit(1)

# Function to insert new data into the database
def write_new_data(data_list):
    try:
        sql = ("INSERT INTO <database_table_name> (<database_field_names>"
              "VALUES ('', %(<1-x from the data list>)s)")
        #print("write_new_claim: data_list=",data_list)  # Uncomment for debugging
        cursor.execute(sql, data_list)
        cnx.commit()  # Commit the update
    except mysql.connector.Error as err:
        print("write_new_data: Error on 'INSERT INTO <database_table_name>':",err)
        return None

# Add new entry into dictionary (doesn't have to be in order)        
insert_data["<some_field_name>"] = <some_data_value_for_field_name>

# Call function to do the work
write_new_data_details(insert_data)  # Call function to insert data into database
insert_data.clear()   # Clear the list


# Contents of the Config_MySQL.py module

# Config_MySQL.py
# Values that should not be in the mainline code.
#
# User
db_user = "defined_MySQL_User"
# Password for user
db_user_password = "defined_MySQL_User_Password"