A script that prepares CSV according to certain rules and generates insert statements from it You can see examples of making similar things with Excel sheets.
What are certain rules?
There is a problem, and CSV alone does not have type information for the table, so it is not possible to determine whether or not it will come with''. In this example, it is all enclosed once. In practice, the idea is to replace it with a regular expression later.
Python 3.7.2 Visual Studio Code 1.39.1
CSV2insSQL.py
#Generate an insert statement from CSV.
#rule
#file name(Excluding the extension)Is the table name
#It is assumed that the csv has a header and the column name matches the DB column name.
#Task!!CSV alone does not have type information for the table, so''I can't judge whether it's big or not
#In this example, it is all enclosed once(Practically, later replace with a regular expression)
import csv
import os
FROM_CSV = '.\\CSV\\' + "xxx_LIST.csv"
def main():
#Body processing
#...Master insert generation
with open(".\\CSV\\insertSQL.txt", "w", newline="",encoding="cp932") as wf:
#From file name to table name
tablename = os.path.splitext(os.path.basename(FROM_CSV))[0]
with open(FROM_CSV, encoding="cp932",) as f:
reader = csv.DictReader(f)
for row in reader:
#insert statement generation
insert_sql = "insert into " + tablename
fields = ",".join(reader.fieldnames)
insert_sql = insert_sql + "( " + fields + ") VALUES"
valuelist = []
for fld in reader.fieldnames:
#Task!!CSV alone does not have type information for the table, so''I can't judge whether it's big or not
#In this example, it is all enclosed once
valuelist.append("'" + row[fld] + "'")
valustr = ",".join(valuelist)
insert_sql = insert_sql + "( " + valustr + ");"
wf.write(insert_sql+"\n")
if __name__ == '__main__': main()