Batch SQL INSERT in Django App



我正在按照此示例将记录批量插入表中,但对其进行修改以适合我的特定示例

sql='INSERT INTO CypressApp_grammatrix (name, row_num, col_num, gram_amount) VALUES {}'.format(', '.join(['(%s, %s, %s, %s)']*len(gram_matrix)),)
    #print sql
    params=[]
    for gram in gram_matrix:
        col_num=1
        for g in gram:            
            params.extend([(matrix_name, row_num, col_num, g)])
            col_num += 1
        row_num += 1
    print params
    with closing(connection.cursor()) as cursor:
        cursor.execute(sql, params)

但是,这样做后,我收到此错误

return cursor._last_executed.decode('utf-8')
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 150, in __getattr__
return getattr(self.cursor, attr)
AttributeError: 'Cursor' object has no attribute '_last_executed'

想知道为什么我会收到此错误以及我可以做些什么来修复它,尽管我觉得问题可能出在与我没有编写的 MySQL 一起使用的代码上

def last_executed_query(self, cursor, sql, params):
    # With MySQLdb, cursor objects have an (undocumented) "_last_executed"
    # attribute where the exact query sent to the database is saved.
    # See MySQLdb/cursors.py in the source distribution.
    return cursor._last_executed.decode('utf-8')

所以我不知道我是否只是拥有 MySQLdb 的旧副本还是什么,但问题似乎出在 cursors.py 上。该文件中唯一可以找到_last_executed的地方在这里

def _do_query(self, q):
    db = self._get_db()
    self._last_executed = q
    db.query(q)
    self._do_get_result()
    return self.rowcount

但是,__init__不会将此变量设置为实例属性。它完全消失了。所以我冒昧地自己添加它并将其初始化为某个查询字符串。我以为任何都可以,所以我只是添加了

class BaseCursor(object):
"""A base for Cursor classes. Useful attributes:
description
    A tuple of DB API 7-tuples describing the columns in
    the last executed query; see PEP-249 for details.
description_flags
    Tuple of column flags for last query, one entry per column
    in the result set. Values correspond to those in
    MySQLdb.constants.FLAG. See MySQL documentation (C API)
    for more information. Non-standard extension.
arraysize
    default number of rows fetchmany() will fetch
"""
from _mysql_exceptions import MySQLError, Warning, Error, InterfaceError, 
     DatabaseError, DataError, OperationalError, IntegrityError, 
     InternalError, ProgrammingError, NotSupportedError
def __init__(self, connection):
    from weakref import ref    
    ...
    self._last_executed ="SELECT * FROM T"
    ...

现在光标对象确实具有属性_last_executed以及何时此函数

def last_executed_query(self, cursor, sql, params):
    # With MySQLdb, cursor objects have an (undocumented) "_last_executed"
    # attribute where the exact query sent to the database is saved.
    # See MySQLdb/cursors.py in the source distribution.
    return cursor._last_executed.decode('utf-8')

在调用base.py中,该属性确实存在,因此此错误

return cursor._last_executed.decode('utf-8')
File "/usr/local/lib/python2.7/dist-
packages/django/db/backends/mysql/base.py", line 150, in __getattr__
return getattr(self.cursor, attr)
AttributeError: 'Cursor' object has no attribute '_last_executed'     

不会遇到。至少我相信它是这样运作的。无论如何,它为我解决了这种情况。

最新更新