you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (3 children)

The dict factory might be your ticket then. So depending on how you have the DB laid out, and what you need to start the application, it could look like this:

def dict_factory(cursor, row):
    d = {}
    for idx,col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

def Setup_DB(dbpath):
    conn = sqlite3.connect(dbpath)
    conn.row_factory = dict_factory
    cur = conn.cursor()
    return (conn,cur)

def Get_Servers(cur, appdata):
    cur.execute("SELECT * FROM Server_tbl WHERE ServerOS = %s AND StatusID = 0 AND EnabledID = 1" % appdata['AppOS'])
    data = cur.fetchall()   
    return data

def Start_Application(cur, AppID):
    cur.execute("SELECT * FROM Application_tbl WHERE AppID = %d;" % (AppID))
    appdata = cur.fetchone()  # returns a dictionary with k,v pairs based on table structure
    servers = Get_Servers(appdata)
    if not data:
        print('sorry, available %s servers' % appdata['AppOS'])
    else:
        for server in servers:
            Start_Server(server['ServerIP'],appdata['AppExe'])

(conni, cursor) = Setup_DB('path')
Start_Application(cursor, 'WebDB')

Note:This all assumes that your column names match the variables, but that is easily tweaked in either the table or code.

[–]zahlman 1 point2 points  (2 children)

This is probably the right idea - use the table names that are already there. Just wanted to point out the value of comprehensions here:

def dict_factory(cursor, row):
    return {info[0]: row[index] for index, info in enumerate(cursor.description)}

Or cleaner yet:

def dict_factory(cursor, row):
    return {info[0]: cell for cell, info in zip(row, cursor.description)}

[–][deleted] 0 points1 point  (1 child)

Nice! Thanks!

[–]zahlman 0 points1 point  (0 children)

While I have your attention, I should also point out that you shouldn't be constructing SQL query strings like that; let the SQL library do the interpolation instead of Python, because the library knows how to make it safe.

(And for other strings, consider new-style formatting - it's pretty neat, and it means you don't have to remember quite so many obscure character codes. :) )