开发者

Help interpreting Python code snippet

I found the below on the web, however from my little exposure with Python I am aware that one can attach functions to object in the fly. I am also aware that everything in Python is object. I am yet to understand what one intend to achieve with the below and its use case. This is the part I need help:

run_sql_command.c = c

def get_sql_object(c):
    def run_sql_command(command, arguments=[]):
        c.execute(command, arguments)
        return c.fetchall()
    run_sql开发者_如何学编程_command.c = c
    return run_sql_command


The idea here (I believe) is that someone is creating a placeholder object that keeps reference to a cursor c so that it may be used to execute queries later. Proposed usage is probably something like this:

c = DBConnectionObject.cursor()

myExecutor = get_sql_object(c)

# some amount of code later
rows = myExecutor(Queries.GetAllUsersByFName, ['Larry', 'Bob'])

-- To address some of the comments --

I find that attempting to keep cursors around can cause problems in volatile environments where it's not always guaranteed that the database connection remains connected. I opt for this approach instead:

class DBConnection(object):
  def __init__(self, dbpath):
    self.dbPath = dbpath

    # Any connection object here, really.
    self._conn = kinterbasdb.connect()

  def cursor(self, query, params = None):
    try:
      cursor = self._conn.cursor()

      if params:
        cursor.execute(query, params)
      else:
        cursor.execute(query)

      return cursor
    except (kdb.ProgrammingError, AttributeError), e:
        print e

  def qry(self, query, params = None):
    cursor = self.cursor(query, params)

    return [[x[0].title() for x in cursor.description]] + [r for r in cursor.fetchall()]

Then, you'd create a global database connection like so:

dbcon = DBConnection('/path/to/mydb.fdb')

and run queries with:

rows = dbcon.qry(Queries.GetSomething)

or:

filtered = dbcon.qry(Queries.FilteredQuery, ['my', 'parameters'])

I've omitted some of the code that does error handling / reconnects to the database if the connection has dropped, but the general idea is there. This way, cursors are created when they're needed, used, and allowed to go out of scope, letting me centralize error handling.


That line adds an attribute c to the function run_sql_command, giving it the value passed to the function get_sql_object(), presumably a database cursor. You probably already knew that much.

With the limited scope of this snippet, the statement has no use at all. In a larger context, the cursor may be re-used elsewhere in the code. Look for accesses to the .c attribute in other parts of the code, and see what's done with it.


I think run_sql_command.c is there to keep an accessible reference to c, e.g. to close it later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜