2012-04-03 3 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で解像度を返し、私は疑問に思いますそれが1を返さない理由を知るために?? おかげ

+3

機能を定義するときに[叫ぶ](http://email.about.com/qt/Writing-In-All-Caps-Is-Like-Shouting.htm)の必要はありません。 [PEP 8](http://www.python.org/dev/peps/pep-0008/)を見てください。 – glglgl

答えて

1

はたぶん表には、そのための前に使用されてきたところでAUTO_INCREMENT> 1 ...

を持っている:私は、これはif get_update_id:は非常にエレガントで繰り返されることはないと思います。あなたはその「基本的なカーソルクラス」としてMySQLdb.cursors.DictCursorを持っているあなたの接続を伝えることができれば代わりに、あなたは

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 

を行うことができ、あなたも、これは自動的にコミットしない

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 

を行うことができます。

関連する問題