Technical Article

Python 3 Script for Generating SQL Insert Statements from CSV Data

,

Introduction:

This Python 3 script is designed to take CSV file data pasted into the csv_data variable and generate SQL insert statements that can be used to insert the data into a MySQL database. The script is easy to use and can save you a lot of time when working with large amounts of data.

Requirements:

To use this script, you will need to have Python 3 installed on your computer. You will also need to have a MySQL database set up and running.

Instructions:

Open a new Python file in your preferred text editor, Copy and paste the following code into the file:

def add_quotes(row):
 values = row.split(",")
 output = ["'{}'".format(value) for value in values]
 return ",".join(output)

def csv_to_mysql(table, csv_data):
 csv_array = csv_data.split("\n")
 header_str = add_quotes(csv_array[1])
 sql_statement = ""
 for row in csv_array[2:-1]:
  row_str = add_quotes(row)
  sql_statement += "INSERT INTO {}({}) VALUES({}); \n".format(table, header_str, row_str)
 return sql_statement

#---------- REPLACE THE BELOW TEXT WITH YOUR CSV DATA----------------
csv_data = """
CustomerID,CustomerName,ContactName,Address,City,PostalCode,Country
89,White Clover,Karl Jablonski,305 - 14th Ave. S. Suite 3B,Seattle,98128,USA
90,Kala Clover,Karl Jablonski,305 - 14th Ave. S. Suite 3B,Seattle,98128,USA
91,Karttunen Clover Markets,Karl Jablonski,305 ,Helsinki,21240,Finland
"""

sql = csv_to_mysql('Customers',csv_data)
print(sql)
print("Execution Finished!")

 

Paste your CSV data into the csv_data variable, replacing the placeholder text and save the file with a .py extension. Now open a command prompt or terminal window and navigate to the directory where the Python file is saved. Run the script by typing "python filename.py" (replace "filename" with the actual name of your file) and pressing Enter.The script will generate SQL insert statements based on the CSV data.

Once the script has finished running, you should see a message indicating that the SQL insert statements were generated and executed successfully.

Example:

Running the script with default hardcoded values produces the following output:

INSERT INTO Customers('CustomerID','CustomerName','ContactName','Address','City','PostalCode','Country') VALUES('89','White Clover','Karl Jablonski','305 - 14th Ave. S. Suite 3B','Seattle','98128','USA'); 
INSERT INTO Customers('CustomerID','CustomerName','ContactName','Address','City','PostalCode','Country') VALUES('90','Kala Clover','Karl Jablonski','305 - 14th Ave. S. Suite 3B','Seattle','98128','USA'); 
INSERT INTO Customers('CustomerID','CustomerName','ContactName','Address','City','PostalCode','Country') VALUES('91','Karttunen Clover Markets','Karl Jablonski','305 ','Helsinki','21240','Finland');

Conclusion:

This Python 3 script is a useful tool for generating SQL insert statements from CSV data and create SQL insert statements for MySQL. By following the instructions in this user guide, you can easily use the script to save time and streamline your data entry process.

def add_quotes(row):
values = row.split(",")
output = ["'{}'".format(value) for value in values]
return ",".join(output)



def csv_to_mysql(table, csv_data):
csv_array = csv_data.split("n")
header_str = add_quotes(csv_array[1])
sql_statement = ""
for row in csv_array[2:-1]:
row_str = add_quotes(row)
sql_statement += "INSERT INTO {}({}) VALUES({}); n".format(table, header_str, row_str)
return sql_statement



#---------- REPLACE THE BELOW TEXT WITH YOUR CSV DATA----------------
csv_data = """
CustomerID,CustomerName,ContactName,Address,City,PostalCode,Country
89,White Clover,Karl Jablonski,305 - 14th Ave. S. Suite 3B,Seattle,98128,USA
90,Kala Clover,Karl Jablonski,305 - 14th Ave. S. Suite 3B,Seattle,98128,USA
91,Karttunen Clover Markets,Karl Jablonski,305 ,Helsinki,21240,Finland
"""



sql = csv_to_mysql('Customers',csv_data)
print(sql)
print("Execution Finished!")

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating