Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. import csv
  2. import os
  3. import pymysql
  4.  
  5. #1ST METHOD
  6. #opens and reads csv file via iteration
  7. with open(raw_input("Input a file path please: ")) as input_file:
  8.        
  9.     #tells you what directory your file is in
  10.     print("You chose this directory that your file is in: " + os.path.realpath(raw_input()))
  11.     #adds space for more readability
  12.     print(" ")
  13.  
  14.     #using a reader, iterate through file
  15.     #will use thisReader variable to call on below with the sql connector method
  16.     thisReader = csv.reader(input_file) #uses built in reader object
  17.     for i in thisReader:
  18.         print i
  19.     input_file.close()
  20.  
  21. ####################################################################################
  22.  
  23. #SECOND METHOD
  24. #connects to mySQL database
  25. mydb = pymysql.connect(host='localhost',
  26.     user='root',
  27.     passwd='',
  28.     db='mydb')
  29. cursor = mydb.cursor()
  30.  
  31. csv_data = csv.reader(file(input_file))
  32. for row in csv_data:
  33.  
  34.     cursor.execute('INSERT INTO testcsv(first name, last name, location, job )' \
  35.           'VALUES("%s", "%s", "%s", "%s")',row)
  36. #close the connection to the database.
  37. mydb.commit()
  38. cursor.close()
  39. print "Done"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement