Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.73 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. ##########################################################################################################################
  3. # Author: Gautham Maroli
  4. # Pre-requisite: Copy all the files (same type) under one directory
  5. # Description: Script is used to verify that all the records in a delimited file is loaded successfully into the DB
  6. # Reads the contents of every file line by line
  7. # Generates a SQL : select query : Depends of the Table used
  8. # And returns success or failure
  9. # In case of Failure- It returns the File Name - Line number in the file
  10. # and the generated SQL query which can be used for further investigation
  11. ##########################################################################################################################
  12. import os
  13. import logging
  14. import csv
  15. import pyodbc
  16.  
  17. logger = logging.getLogger("DBFileloadCheckinDB")
  18. logger.setLevel(logging.DEBUG)
  19.  
  20. # create file handler which logs even debug messages
  21. fh = logging.FileHandler('validatedbload.log', 'w') # overwrite the log file
  22. fh.setLevel(logging.DEBUG)
  23. # create console handler with a higher log level
  24. ch = logging.StreamHandler()
  25. ch.setLevel(logging.ERROR)
  26. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  27. fh.setFormatter(formatter)
  28. ch.setFormatter(formatter)
  29. # add the handlers to the logger
  30. logger.addHandler(fh)
  31. logger.addHandler(ch)
  32.  
  33.  
  34. def processfile(fpath, filedelimilter, header):
  35. server = 'server-name'
  36. database = 'db-name'
  37. username = 'db-useruname'
  38. password = 'db-password'
  39. driver = '{ODBC Driver 13 for SQL Server}'
  40.  
  41. cnxn = pyodbc.connect('DRIVER=' + driver + ';SERVER=' + server + ';PORT=1433;DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
  42. cursor = cnxn.cursor()
  43.  
  44. # verify if the directory exits
  45. try:
  46. os.chdir(fpath)
  47. logger.info("File path is valid: {}".format(fpath))
  48. # Get the File name:
  49. for f in os.listdir(fpath):
  50. with open(f, 'r') as filetoprocess:
  51. delimitedfile = csv.reader(filetoprocess, delimiter=filedelimilter)
  52. if header: # skip the header
  53. next(delimitedfile)
  54. for i, row in enumerate(delimitedfile):
  55. i = i + 1
  56. if "'" in row[5]:
  57. row[5] = row[5].replace("'", "''") # if there is a '(single quote) in the string replace it so that query does not fail
  58. query = "select * from Customers " \
  59. "where" \
  60. "[Id] = '" + row[0].strip() + "' and " \
  61. "[FirstName]='" + row[1].strip() + "' and " \
  62. "[LastName]='" + row[2].strip() + "' and " \
  63. "[Email]='" + row[3].strip() + "' and " \
  64. "[Gender]='" + row[4].strip() + "' and " \
  65. "[Address]='" + row[5].strip() + "' and " \
  66. "[PhoneNum]='" + row[6].strip()
  67. logger.error("Unprocessed Record LineNum: {}, FileName: {} -- sql: {}".format(i, f, query))
  68. logger.info(query)
  69. cursor.execute(query)
  70. datarow = cursor.fetchone()
  71. if datarow:
  72. if i % 10 == 0: # This value can be changed if the file has more records
  73. logger.info("Processed Records: {}".format(i))
  74. else:
  75. logger.error("Unprocessed Records: {} -- sql: {}".format(i, query))
  76.  
  77. except FileNotFoundError:
  78. logger.error("Invalid file path: {}".format(fpath))
  79.  
  80.  
  81. if __name__ == '__main__':
  82. processfile(input("enter the file location: "), ",", True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement