To write data from a CSV file to a SQL database using Python, you can use the csv
and pyodbc
libraries to read the CSV file and write the data to the SQL database. Here’s an example code
import csv import pyodbc # Connect to the SQL database conn = pyodbc.connect('Driver={SQL Server};Server=server_name;Database=database_name;Trusted_Connection=yes;') # Open the CSV file and read the data with open('data.csv', 'r') as file: reader = csv.reader(file) next(reader) # skip header row for row in reader: # Insert the row into the database cursor = conn.cursor() cursor.execute("INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)", row[0], row[1], row[2]) conn.commit() # Close the database connection conn.close()
In this example, the CSV file data.csv
contains the data to be inserted into the SQL database. The csv.reader()
method reads the file and iterates through the rows, skipping the header row using the next()
method. For each row, a SQL query is executed to insert the row into the table_name
table in the SQL database. The cursor.execute()
method uses parameterized queries to insert the values from the CSV row into the SQL query. The commit()
method commits the transaction to the database. Finally, the database connection is closed using the conn.close()
method. You can modify the SQL query and column names to match the structure of your database and CSV file.