csv2db.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import sqlite3
  2. import csv
  3. # Define the input CSV file and the SQLite database file
  4. input_csv = 'nba_roster.csv'
  5. database_file = 'nba_roster.db'
  6. # Connect to the SQLite database
  7. conn = sqlite3.connect(database_file)
  8. cursor = conn.cursor()
  9. # Create a table to store the data
  10. cursor.execute('''CREATE TABLE IF NOT EXISTS nba_roster (
  11. Team TEXT,
  12. NAME TEXT,
  13. Jersey TEXT,
  14. POS TEXT,
  15. AGE INT,
  16. HT TEXT,
  17. WT TEXT,
  18. COLLEGE TEXT,
  19. SALARY TEXT
  20. )''')
  21. # Read data from the CSV file and insert it into the SQLite table
  22. with open(input_csv, 'r', newline='') as csvfile:
  23. csv_reader = csv.reader(csvfile)
  24. next(csv_reader) # Skip the header row
  25. for row in csv_reader:
  26. cursor.execute('INSERT INTO nba_roster VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', row)
  27. # Commit the changes and close the database connection
  28. conn.commit()
  29. conn.close()
  30. print(f'Data from {input_csv} has been successfully imported into {database_file}')