2012-04-03 66 views
0

下面是我RUN_SQL功能:爲什麼「cursor.lastrowid」返回3?

def RUN_SQL_SAFE(sql, input_tuple=(), get_update_id=False, debug = False): 
    conn = GET_MYSQL_CONNECTION() 
    cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) 
    cursor.execute(sql, input_tuple) 
    conn.commit() 
    if get_update_id: 
     res = cursor.lastrowid 
    cursor.close() 
    conn.close() 
    if get_update_id: 
     return res 

我運行使用「RUN_SQL_SAFE(SQL,元組,真)」,這裏的SQL是一個插入SQL和表是空的,但有3回RES我不知道我的代碼知道爲什麼它不會返回1? 感謝

+3

定義函數時,不需要[留言](http://email.about.com/od/netiquettetips/qt/Writing-In-All-Caps-Is-Like-Shouting.htm)。看看[PEP 8](http://www.python.org/dev/peps/pep-0008/)。 – glglgl 2012-04-03 07:29:22

回答

1

也許表一直在使用的前,因此有AUTO_INCREMENT> 1 ...

BTW:我不認爲這重複if get_update_id:很優雅。相反,你可以做

def run_sql_safe(sql, input_tuple=(), get_update_id=False, debug = False): 
    from contextlib import closing 
    conn = get_mysql_connection() 
    with closing(conn): 
     cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) 
     with closing(cursor): 
      cursor.execute(sql, input_tuple) 
      conn.commit() 
      if get_update_id: 
       return cursor.lastrowid 

如果你能告訴你的連接有MySQLdb.cursors.DictCursor作爲其「基本指針類」,你甚至可以做

def run_sql_safe(sql, input_tuple=(), get_update_id=False, debug = False): 
    from contextlib import closing 
    conn = get_mysql_connection(cursorclass=MySQLdb.cursors.DictCursor) 
    with closing(conn): 
     with conn as cursor: 
      cursor.execute(sql, input_tuple) 
      if get_update_id: 
       return cursor.lastrowid 

其執行此自動提交。