Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mportocarrero/8373721 to your computer and use it in GitHub Desktop.
Save mportocarrero/8373721 to your computer and use it in GitHub Desktop.
Populating new table - MySql and Python To insert data into the new table I used MySql. I could have used Python as well as both ways work, but MySql makes it more visual and easier to use.
mysql> LOAD DATA LOCAL INFILE "cycling.csv" INTO TABLE cycling FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r' IGNORE 1 LINES;
Query OK, 5 rows affected, 1 warning (0.00 sec)
Records: 5 Deleted: 0 Skipped: 0 Warnings: 1
mysql> select * from cycling;
+---------------+-----------+-----------+-----------------+-----------+-----------+-----------------+-------------------+
| Borough | Work_2001 | Bike_2001 | Percentage_2001 | Work_2011 | Bike_2011 | Percentage_2011 | Percentage_change |
+---------------+-----------+-----------+-----------------+-----------+-----------+-----------------+-------------------+
| Croydon | 156838 | 1636 | 1.0 | 172987 | 2172 | 1.3 | 0.3 |
| Greenwich | 91575 | 1351 | 1.5 | 117821 | 2738 | 2.3 | 0.8 |
| Hackney | 79232 | 4929 | 6.2 | 118556 | 17312 | 9.9 | 8.4 |
| Lewisham | 114592 | 2112 | 1.8 | 136057 | 5375 | 4.0 | 2.1 |
| Tower Hamlets | 73918 | 2214 | 3.0 | 120873 | 8112 | 6.7 | 3.7 |
+---------------+-----------+-----------+-----------------+-----------+-----------+-----------------+-------------------+
5 rows in set (0.00 sec)
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user='co302mc',
passwd='mafol597',
db='co302mc_bike_theft')
cursor = mydb.cursor()
csv_data = csv.reader(file('cycling.csv'))
for row in csv_data:
cursor.execute("INSERT INTO cycling(Borough, Work_2001, Bike_2001, Percentage_2001, Work_2011, Bike_2011, Percentage_2011, Percentage_change) VALUES(%s, %s, %s, %s, %s, %s, %s, %s)", row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
@raina99
Copy link

raina99 commented Jan 5, 2018

TypeError: %d format: a number is required, not str

it gives this error also file() is not defined although open() works quite well in its place

@Janethjepkogei
Copy link

Janethjepkogei commented Feb 23, 2018

Getting the same error above too. Any ideas on how to fix it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment