Guest User

Untitled

a guest
May 21st, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. import MySQLdb as mysql
  2.  
  3. db = None
  4.  
  5. # Connect to database
  6. def connect(host, user, password, db_name):
  7. global db
  8. db = mysql.connect(host=host, user=user, passwd=password, db=db_name)
  9.  
  10. # Build result as a dict
  11. def build_query_result(cursor):
  12. columns = list(map(lambda item: item[0], cursor.description))
  13. return list(map(lambda item: { column: item[index] for (index,column) in enumerate(columns) }, cursor.fetchall()))
  14.  
  15. # Run a query
  16. def query(sql, params=[]):
  17. global db
  18. c = db.cursor()
  19. c.execute(sql, tuple(params))
  20. return build_query_result(c)
  21.  
  22. # Run an update
  23. def update(sql, params=[]):
  24. global db
  25. c = db.cursor()
  26. c.execute(sql, tuple(params))
  27. db.commit()
  28. return (c.lastrowid, c.rowcount)
Add Comment
Please, Sign In to add comment