Python TypeError:“Field”对象不可调用:msql-connector-python

Python TypeError: 'Field' object is not callable: msql-connector-python

提问人:Nulla 提问时间:8/24/2023 更新时间:8/24/2023 访问量:60

问:

问题:使用“mysql-connector-python”库执行某个 UPDATE 查询会导致 utf8 编码期间出现 TypeError。

我的项目中的包:

colorama==0.4.6
iniconfig==2.0.0
mysql-connector-python==8.1.0
packaging==23.1
pluggy==1.2.0
protobuf==4.21.12
PyPika==0.48.9
pytest==7.4.0
python-dotenv==1.0.0

这是我从 PyPika 创建的 UPDATE 查询:

UPDATE `companyconfig`.`routing` SET `SequenceNumber`='4' WHERE `SiteGuid`='{AAAA-AAAA-AAAA-AAAA}' AND `Type`='directories'

这是我的查询生成器:

def get_update_system_site_directory_lookup_index_query(site_guid: str, sequence_number: int):
    # Using PyPika for this query building
    schema = Schema('companyconfig')
    table = Table('routing', schema)
    return MySQLQuery.update(table) \
        .set(table.SequenceNumber, str(sequence_number)) \
        .where((table.SiteGuid == site_guid) & (table.Type == 'directories'))

def fix_directory_lookup_indexes():
    # update_query becomes: UPDATE `companyconfig`.`routing` SET `SequenceNumber`='4' WHERE `SiteGuid`='{AAAA-AAAA-AAAA-AAAA}' AND `Type`='directories'
    update_query = get_update_system_site_directory_lookup_index_query('{AAAA-AAAA-AAAA-AAAA}', 4)

    query_result = connection.cursor.execute(update_query)

下面是堆栈跟踪:

Traceback (most recent call last):
  File "C:\dev\service-xyz\service.py", line 16, in fix_directory_lookup_indexes
    query_result = connection.cursor.execute(update_query)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\dev\service-xyz\xyz\db.py", line 19, in execute
    connection.cursor.execute(query)
  File "C:\dev\service-xyz\venv\Lib\site-packages\mysql\connector\cursor_cext.py", line 330, in execute
    result = self._cnx.cmd_query(
             ^^^^^^^^^^^^^^^^^^^^
  File "C:\dev\service-xyz\venv\Lib\site-packages\mysql\connector\opentelemetry\context_propagation.py", line 77, in wrapper
    return method(cnx, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\dev\service-xyz\venv\Lib\site-packages\mysql\connector\connection_cext.py", line 632, in cmd_query
    query = query.encode("utf-8")
            ^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Field' object is not callable

在执行查询之前,我可以判断查询生成器的输出是正确的。我在 SQL Server 上测试了确切的查询,它起作用了,但是当我尝试通过连接器执行时,我得到了 TypeError。

我不确定为什么由于字符串被编码而出现此错误,并且我无法找到真正的问题所在。

有人有什么想法吗?

问候和感谢,

L

sql mysql mysql-connector-python pypika

评论

0赞 snakecharmerb 8/24/2023
看看 pypika 项目 README,你不应该通过还是去?str(update_query)update_query.get_sql()cursor.execute
0赞 Nulla 8/24/2023
做到了!谢谢!

答:

0赞 Nulla 8/24/2023 #1

使用 str(update_query) 来解决这个问题。感谢用户@snakecharmerb!