-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLoadFromCSV.py
54 lines (44 loc) · 1.59 KB
/
LoadFromCSV.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'''
Created on Nov 23, 2015
@author: ashish
'''
import imp
#imp.load_source("config","/cygdrive/c/Users/ashish/Desktop/workspace/NSEDataAnalytics/neoPath/config.py")
import MySQLdb
from dateutil.parser import parse
import datetime
import time
import csv
import config
from config import type
from config import tests
def insert_into_database(File,database,single_or_many):
db=MySQLdb.connect(config.host,config.user,config.password,config.database)
cursor=db.cursor()
try:
csv_data=csv.reader(file(File))
format=",".join(["%s" for m in range(0,len(csv_data.next()))])
if single_or_many:
for row in csv_data:
data=[int(m) if type(m)==int else float(m) if type(m)==float else parse(m).strftime("%Y-%m-%d %H:%M:%S") if type(m)==datetime else m for m in row]
try:
cursor.execute("insert into %s values(%s)"%(database,format),data)
db.commit()
except MySQLdb.Error as e:
raise
else:
data=list(csv_data)
try:
format=",".join(["%s" for m in range(0,len(data[0]))])
cursor.executemany("insert into %s values(%s)"%(database,format),data)
db.commit()
except MySQLdb.Error as e:
raise
except IOError:
raise
finally:
db.close()
if __name__ == '__main__':
File=r"C:\Users\ashish\Downloads\NeoFeedPlus (1)\data_20151123_v1.csv"
database="test"
insert_into_database(File,database,1)