Guest User

Untitled

a guest
May 10th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. import csv
  2. import pymysql
  3.  
  4. # you may have to install pymysql. The command is 'pip install pymysql'
  5.  
  6. # This script will load a file (sample.csv) into the database
  7. # put the filename and path you want to load
  8.  
  9. load_path = 'C:/code/samples/ICES_biota.csv'
  10. load_file = 'ICES_biota.csv'
  11.  
  12. connection = pymysql.connect(host='tesla.epa.gov',
  13. port=3306,
  14. user='your_username',
  15. password='your_password',
  16. db='prod_samples',
  17. use_unicode=True,
  18. charset="utf8")
  19. cursor = connection.cursor()
  20.  
  21.  
  22. # insert the file into the sources table
  23. sql = "INSERT INTO prod_samples.source (filename) VALUES ('%s')" % load_file
  24. cursor.execute(sql)
  25. connection.commit()
  26.  
  27. # grab the id of the source just inserted to add to the sample table
  28. sql = "SELECT id FROM source WHERE filename = '%s'" % load_file
  29. cursor.execute(sql)
  30. fk_source_id = cursor.fetchone()
  31.  
  32. # open up the csv - utf-8 encoding is super important here
  33. reader = csv.DictReader(open(load_file, encoding='utf-8'))
  34.  
  35. # get the column names
  36. column_names = reader.fieldnames
  37.  
  38. # read the rows and columns and insert the info into the database
  39. for row in reader:
  40. for column in column_names:
  41. # only load the sample column if there is a value in it :)
  42. if row[column] != '':
  43. sql = "INSERT INTO sample (variable_name, variable_value, fk_source) VALUES ('%s', '%s', %i)" % \
  44. (column, row[column], fk_source_id[0])
  45. cursor.execute(sql)
  46. connection.commit()
  47.  
  48. connection.close()
  49. print('done!')
Add Comment
Please, Sign In to add comment