Advertisement
Guest User

Untitled

a guest
Aug 9th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. Firstly import below modules in Python file or Django file .
  2. 1. csv
  3. 2. psycopg2
  4. Now Firstly create a connection with your database below way
  5. try:
  6. conn_string="dbname='user database name' user='database user name' host='localhost' password='your user password'"
  7. print ("Connecting to database\n->%s" % (conn_string))
  8. conn = psycopg2.connect(conn_string)
  9. print ("connection succeeded")
  10. except:
  11. print ("no connection to db")
  12. Hope if you insert correctly your database information. It should work.
  13. Now go next step.
  14. Now collect your data from csv file below way . I gave an example below
  15. My CSV data Sctucture was below
  16. Call 43,234234223,2017/08/08 06:47:21
  17. Call 44,234234234,2017/08/08 06:47:26
  18. Call 45,987654443,2017/08/08 06:47:30
  19. Call 46,Ext.301,2017/08/08 07:01:34
  20. with open("your file location", newline='') as csvfile:
  21. spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
  22. s = []
  23. for row in spamreader:
  24. s.append(row)
  25. s2 = filter(None, s)
  26. ids = []
  27. numbers = []
  28. dateDtime = []
  29. for i in s2:
  30. if i[1] == 'Ext.301':
  31. continue
  32. else:
  33. numbers.append(i[1])
  34. ids.append(i[0])
  35. dateDtime.append(i[2])
  36. idnumber = [i.split(' ')[1] for i in ids]
  37. date = [i.split(' ')[0] for i in dateDtime]
  38. time = [i.split(' ')[1]for i in dateDtime]
  39. t = tuple(zip(idnumber,numbers,date,time))
  40. # check connection
  41. cur = conn.cursor()
  42. cur.executemany("INSERT INTO csv_data (id, call_numbers, call_date,call_time) VALUES (%s,%s, %s, %s)", t);
  43. # Make the changes to the database persistent
  44. conn.commit()
  45. # Close communication with the database
  46. cur.close()
  47. conn.close()
  48. My tuple was look like below. If you try to above data , you must get tuple look like this.
  49. (('43', '234234223', '2017/08/08', '06:47:21'), ('44', '234234234', '2017/08/08', '06:47:26'),('45', '987654443', '2017/08/08', '06:47:30'))
  50. executemany means in a time it will execute many tuple data.
  51. That's all . Thanks
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement