Guest User

Untitled

a guest
Feb 18th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. import pyodbc import _csv
  2.  
  3. source_path= r'C:UsersuserDocumentsQA Canvasmodule2Module 2 ChallengeUFO_Merged.csv'
  4.  
  5. source_expand= open(source_path, 'r')
  6.  
  7. details= source_expand.readlines
  8.  
  9. print('Connecting...')
  10. try:
  11. conn = pyodbc.connect(r'DRIVER={ODBC Driver 13 for SQL Server};'r'SERVER=FAHIMSQLEXPRESS;'r'DATABASE=Ash;'r'Trusted_Connection=yes')
  12. print('Connected')
  13. cur = conn.cursor()
  14. print('Cursor established')
  15.  
  16. sqlquery ="""
  17. IF EXISTS
  18. (
  19. SELECT TABLE_NAME ,TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'UFO_MERGED' AND TABLE_SCHEMA = 'dbo')
  20.  
  21. BEGIN
  22. DROP TABLE [dbo].[UFO_MERGED]
  23. END
  24.  
  25. CREATE TABLE [dbo].[UFO_MERGED]
  26. ( [ID] smallint
  27. ,[COMMENTS] varchar(max)
  28. ,[FIRST OCCURANCE] datetime
  29. ,[CITY] varchar(60)
  30. ,[COUNTRY] varchar(20)
  31. ,[SHAPE] varchar(20)
  32. ,[SPEED] smallint
  33. ,[SECOND OCCURANCE] datetime
  34. PRIMARY KEY(id)
  35. ) ON [PRIMARY]
  36.  
  37. """
  38. result = cur.execute(sqlquery).fetchall()
  39. for row in result:
  40. print(row)
  41. print("{} rows returned".format(len(result)))
  42.  
  43. sqlstr= """
  44. Insert into [dbo].[UFO_Merged] values ('(),'(),'(),'(),'(),'(),'(),'(),)
  45.  
  46. """
  47.  
  48. for row in details[1:]:
  49. row_data =row.split(',')
  50. sqlquery=sqlstr.format(row_data[0],row_data[1],row_data[2],row_data[3],row_data[4],row_data[5],row_data[6],row_data[7])
  51. result=cur.execute(sqlquery)
  52.  
  53. conn.commit()
  54. conn.close()
  55.  
  56.  
  57. except Exception as inst:
  58. if inst.args[0]== '08001':
  59. print("Cannot connect to the server")
  60. elif inst.args[0] == '28000':
  61. print("Login failed - check connection string")
  62. else:
  63. print(inst)
Add Comment
Please, Sign In to add comment