Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mportocarrero/8318296 to your computer and use it in GitHub Desktop.
Save mportocarrero/8318296 to your computer and use it in GitHub Desktop.
Query 1 - How many bikes were stolen in the boroughs between May and October 2013? (MySql and Python) To answer this question I simply counted all the rows of the table, as each one represents one stolen bike. This first query was to make the readers familiar to which amount of I would be working from then on.
Query on MySql:
mysql> select count(*) from bike as total;
+----------+
| count(*) |
+----------+
| 321 |
+----------+
1 row in set (0.00 sec)
Output results in a csv file using Python:
import pymysql, sys
import csv
try:
conn = pymysql.connect(host='localhost',
port=3306,
user='co302mc',
passwd='mafol597',
db='co302mc_bike_theft')
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM bike")
data = cur.fetchall()
c = csv.writer(open("total.csv","wb"))
for row in data:
print row
c.writerow(row)
except Exception as e:
print "couldn't connect to database",e
sys.exit()
Note: I do not use MySql to output my results in a csv file because the permissions were denied. Although, that was the code I was going to use:
mysql> SELECT COUNT(*)
    -> INTO OUTFILE '/tmp/total.csv'
    -> FIELDS TERMINATED BY','
    -> ENCLOSED BY '"'
    -> ESCAPED BY '\\'
    -> LINES TERMINATED BY '\n'
    -> FROM bike;
ERROR 1045 (28000): Access denied for user 'co302mc'@'%' (using password: YES)
mysql> GRANT ALL ON co302mc_last.* TO 'co302mc'@'igor';
ERROR 1044 (42000): Access denied for user 'co302mc'@'%' to database 'co302mc_last'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment