mantawolf

InventoryImportPython

Jun 23rd, 2015
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. import csv
  2. import MySQLdb
  3. import datetime
  4.  
  5. mydb = MySQLdb.connect(
  6.     host="localhost",
  7.     user="root",
  8.     passwd="somepassword",
  9.     db="autoinventory"
  10. )
  11.  
  12. cursor = mydb.cursor()
  13. rowOne = 0
  14.  
  15. csv_data = csv.reader(file("autoinventory.csv"))
  16. for row in csv_data:
  17.     if rowOne == 1:
  18.         carDataSql = (
  19.             "INSERT INTO CarDetail ( "
  20.                 "  StockNumber"
  21.                 ", Make"
  22.                 ", Model"
  23.                 ", Year"
  24.                 ", VIN"
  25.                 ", Price"
  26.                 ", DateAquired"
  27.             " ) "
  28.             "VALUES( %s, %s, %s, %s, %s, %s, %s )"
  29.         )
  30.  
  31.             carData = (
  32.                   row[0]
  33.                 , row[1]
  34.                 , row[2]
  35.                 , int(row[3])
  36.                 , row[4]
  37.                 , float(row[5])
  38.                 , datetime.datetime.strptime(row[6], "%b %d %Y %I:%M%p").date()
  39.             )
  40.            
  41.             cursor.execute( carDataSql, carData )
  42.  
  43.             carOptions = row[7].split(",")
  44.             carImages = row[8].split(";")
  45.            
  46.             for option in carOptions:
  47.                 optionSql = (
  48.                         "INSERT INTO CarOption ( StockNumber, OptionText ) "
  49.                         "VALUES ( %s, %s )"
  50.                 )
  51.  
  52.                 optionData = ( row[0], option )
  53.                 cursor.execute( optionSql, optionData )
  54.  
  55.             for image in carImages:
  56.                 imageSql = (
  57.                         "INSERT INTO CarImage ( StockNumber, ImageURL ) "
  58.                         "VALUES ( %s, %s )"
  59.                 )
  60.  
  61.                 imageData = ( row[0], image )
  62.                 cursor.execute( imageSql, imageData )
  63.  
  64.     rowOne = 1
  65. mydb.commit()
  66. cursor.close()
Advertisement
Add Comment
Please, Sign In to add comment