MCPcopy Create free account
hub / github.com/ActiveState/code / SqlExecute

Function SqlExecute

recipes/Python/578977_Python_SQLSMO_/recipe-578977.py:12–52  ·  view source on GitHub ↗

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='')

Source from the content-addressed store, hash-verified

10
11# --------------Functions-----------------------------------------------------------------------------
12def 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
55def GetLatestBackup(dirpath, filter='\*.*'):

Callers 9

KillConnectionsFunction · 0.85
SyncLoginsFunction · 0.85
GetDataseInfoMethod · 0.85
GetBackupInfoMethod · 0.85
GetFreeSpaceMethod · 0.85
RestoreDatabaseMethod · 0.85
BackupDatabaseMethod · 0.85
recipe-578977.pyFile · 0.85
ActionParsingFunction · 0.85

Calls 6

printFunction · 0.85
communicateMethod · 0.80
keysMethod · 0.45
decodeMethod · 0.45
splitMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected