biblioteca_fc/csv2bfc.py

37 lines
894 B
Python
Raw Normal View History

2023-05-30 17:45:00 +01:00
import sys,csv
import mysql.connector
def main():
connection = mysql.connector.connect(user='root', password='123',
host='127.0.0.1',
database='biblioteca_fc')
file = open(sys.argv[1],"r")
lines = csv.reader(file)
#Get name and order of columns
columns = next(lines)
#Replace empty values with null
values = [[value if value else None for value in line] for line in lines]
#Create placeholder strings
placeholders = ', '.join(['%s'] * len(columns))
#Create query
query = f"INSERT INTO Utilizador ({', '.join(columns)}) VALUES ({placeholders})"
#Execute query
cursor = connection.cursor()
cursor.executemany(query,values)
connection.commit()
#Close everything
file.close()
cursor.close()
connection.close()
if __name__ == "__main__":
main()