Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1#!/usr/local/bin/python 

2# encoding: utf-8 

3""" 

4*Given a mysql query, read the data from the database and return the results as a list of dictionaries (database rows)* 

5 

6:Author: 

7 David Young 

8 

9:Date Created: 

10 June 21, 2016 

11""" 

12################# GLOBAL IMPORTS #################### 

13from builtins import str 

14import sys 

15import os 

16os.environ['TERM'] = 'vt100' 

17from fundamentals import tools 

18 

19 

20def readquery( 

21 sqlQuery, 

22 dbConn, 

23 log, 

24 quiet=False): 

25 """Given a mysql query, read the data from the database and return the results as a list of dictionaries (database rows) 

26 

27 **Key Arguments:** 

28 - ``log`` -- the logger. 

29 - ``sqlQuery`` -- the MySQL command to execute 

30 - ``dbConn`` -- the db connection 

31 - ``quiet`` -- ignore mysql warnings and errors and move on. Be careful when setting this to true - damaging errors can easily be missed. Default *False*. 

32 

33 **Return:** 

34 - ``rows`` -- the rows returned by the sql query 

35 

36 **Usage:** 

37 

38 .. code-block:: python 

39 

40 from fundamentals.mysql import readquery 

41 rows = readquery( 

42 log=log, 

43 sqlQuery=sqlQuery, 

44 dbConn=dbConn, 

45 quiet=False 

46 ) 

47 """ 

48 log.debug('starting the ``readquery`` function') 

49 import pymysql 

50 import warnings 

51 warnings.filterwarnings('error', category=pymysql.Warning) 

52 

53 rows = [] 

54 

55 try: 

56 cursor = dbConn.cursor(pymysql.cursors.DictCursor) 

57 except Exception as e: 

58 log.error('could not create the database cursor: %s' % (e, )) 

59 raise IOError('could not create the database cursor: %s' % (e, )) 

60 # EXECUTE THE SQL COMMAND 

61 try: 

62 cursor.execute(sqlQuery) 

63 rows = cursor.fetchall() 

64 except Exception as e: 

65 sqlQuery = sqlQuery[:1000] 

66 if quiet == False: 

67 log.warning( 

68 'MySQL raised an error - read command not executed.\n' + str(e) + '\nHere is the sqlQuery\n\t%(sqlQuery)s' % locals()) 

69 raise e 

70 else: 

71 log.warning( 

72 'MySQL raised an error - read command not executed.\n' + str(e) + '\nHere is the sqlQuery\n\t%(sqlQuery)s' % locals()) 

73 pass 

74 

75 # CLOSE THE CURSOR 

76 try: 

77 cursor.close() 

78 except Exception as e: 

79 log.warning('could not close the db cursor ' + str(e) + '\n') 

80 

81 log.debug('completed the ``readquery`` function') 

82 return rows