I am trying to get a CSV file to a MYSQL database, but it never appears! I dont know if I messed something up, but you guys should take a look.
# its time for fetching data :)
import csv
import urllib2
path = 'C:\\Users\\User\\Desktop\\Downloads\\'
response = urllib2.urlopen('https://files.ontario.ca/opendata/births_by_year_and_month_per_place_of_event_city_2010_0.csv')
html = response.read()
file=open( path +"births.CSV", "r")
reader = csv.reader(file)
for row in reader:
print row
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="admin",
db="cool")
x = conn.cursor()
try:
x.execute("""INSERT INTO import (test) VALUES (%s,%s,%s,%s)""",(row))
conn.commit()
except:
conn.rollback()
conn.close()
It ends with exit code 0, prints everything, but never inserts into the database. Here is a sample of the print
['2010', 'Sep', 'THUNDER BAY', '132']
['2010', 'Sep', 'TIMMINS', '59']
['2010', 'Sep', 'TORONTO', '3412']
['2010', 'Sep', 'WELLAND', '58']
['2010', 'Sep', 'WELLINGTON NORTH', '6']
['2010', 'Sep', 'WINDSOR', '337']
['2010', 'Sep', 'WOODSTOCK', '50']
Process finished with exit code 0
EDIT Im not sure if the %s part has something to do with it, but i need help. Thanks!
Edit 2 Great! Thanks to all of you people who have helped me. But now there's a new edit, and i cant seem to find out whats going wrong. Here is the new code!
import csv
import urllib2
path = 'C:\\Users\\hongyu\\Desktop\\Downloads\\'
response = urllib2.urlopen('https://files.ontario.ca/opendata/births_by_year_and_month_per_ place_of_event_city_2010_0.csv')
html = response.read()
file=open( path +"births.CSV", "r")
reader = csv.reader(file)
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="admin",
db="cool")
for row in reader:
x = conn.cursor()
try:
x.execute("""INSERT INTO testing (year, month, city, num) VALUES (%s,%s,%s,%s)""", (row))
conn.commit()
except :
conn.rollback()
print(row)
print("This row failed to insert")
conn.close()
Now when I run the code, it would tell me what row failed to insert. But there were alot of rows that failed. Here is a bit of the result.
['1994', 'Dec', 'KAPUSKASING', '10']
This row failed to insert
['1994', 'Dec', 'KENORA', '29']
This row failed to insert
['1994', 'Dec', 'KINCARDINE', '11']
This row failed to insert
['1994', 'Dec', 'KINGSTON', '198']
This row failed to insert
['1994', 'Dec', 'KIRKLAND LAKE', '13']
This row failed to insert
['1994', 'Dec', 'KITCHENER', '363']
This row failed to insert
['1994', 'Dec', 'LEAMINGTON', '31']
This row failed to insert
Any help? the database is missing almost everything, and here is a little bit of that. http://prntscr.com/h6dhod P.S: Its not just citys starting with a, there is also Toronto.
except:block.