python process mysql query
import MySQLdb
#pip install mysql-python
db = MySQLdb.Connect('mysqlhost',
'liji', 'xxx', 'dbname')
fo = open("spread.csv", "a+")
while True:
c = db.cursor()
c.execute("""(SELECT `order`.`price` AS `price`, sum(`order`.`amount`) AS `amount`,`order`.`type` AS `type`, UNIX_TIMESTAMP(CURRENT_TIMESTAMP())
FROM `order` WHERE (`order`.`amount` > 0) AND (`order`.`cancelled` = 0) AND (`order`.`type` = 'ask') AND `user_id` <> 391695 and `user_id` <> 445847 group by price order by price limit 1)
union
(SELECT `order`.`price` AS `price`, sum(`order`.`amount`) AS `amount`,`order`.`type` AS `type`, UNIX_TIMESTAMP(CURRENT_TIMESTAMP())
FROM `order` WHERE (`order`.`amount` > 0) AND (`order`.`cancelled` = 0) AND (`order`.`type` = 'bid') AND `user_id` <> 391695 and `user_id` <> 445847 group by price order by price desc limit 1);""")
ask = c.fetchone()
bid = c.fetchone()
ask1price = ask[0]
bid1price = bid[0]
timestamp = ask[3]
print "%s, %s, %s"%(ask1price, bid1price, timestamp)
fo.write("%s, %s, %s\n"%(ask1price, bid1price, timestamp))
fo.flush()
db.commit()
c.close()