Executes sqlquery and returns lists with column names and data The connection info is passed as a dictionary with these required keys: servername, username,password If username is empty will use integrated security These keys are optional: defdb, colseparator
(conn, sqlquery='')
| 10 | |
| 11 | # --------------Functions----------------------------------------------------------------------------- |
| 12 | def SqlExecute(conn, sqlquery=''): |
| 13 | |
| 14 | """ |
| 15 | Executes sqlquery and returns lists with column names and data |
| 16 | The connection info is passed as a dictionary with these required keys: |
| 17 | servername, username,password |
| 18 | If username is empty will use integrated security |
| 19 | These keys are optional: defdb, colseparator |
| 20 | """ |
| 21 | |
| 22 | if 'colseparator' not in conn.keys(): |
| 23 | conn['colseparator'] = chr(1) |
| 24 | if conn['username'] == '': |
| 25 | constr = "sqlcmd -E -S" + conn['servername'] + " /w 8192 -W " + ' -s' + conn['colseparator'] + ' ' |
| 26 | else: |
| 27 | constr = "sqlcmd -U" + conn['username'] + " -P" + conn['password'] + ' -S' + conn['servername'] + ' /w 8192 -W -s' + conn['colseparator'] + ' ' |
| 28 | |
| 29 | # now we execute |
| 30 | try: |
| 31 | data = subprocess.Popen(constr + '-Q"' + sqlquery + '"', stdout=subprocess.PIPE).communicate() |
| 32 | except Exception as inst: |
| 33 | print('Exception in SqlExecute:', inst) |
| 34 | return -1 |
| 35 | |
| 36 | records = [] |
| 37 | lst = data[0].splitlines() |
| 38 | # lst[0] column names; lst[1] dashed lines, (skip); lst[2:] data |
| 39 | # now we decode |
| 40 | for x in lst: |
| 41 | try: |
| 42 | #try default utf-8 decoding |
| 43 | line = x.decode() |
| 44 | except UnicodeDecodeError: |
| 45 | #in case of weird characters this one works most of the time |
| 46 | line = x.decode('ISO-8859-1') |
| 47 | lst2 = line.split(conn['colseparator']) |
| 48 | records.append(lst2) |
| 49 | fieldnames = records[0] |
| 50 | data = records[2:] |
| 51 | |
| 52 | return data, fieldnames |
| 53 | |
| 54 | |
| 55 | def GetLatestBackup(dirpath, filter='\*.*'): |
no test coverage detected