python - 在 Python 中使用 mysql.connector 处理格式参数失败

标签 python mysql

我无法弄清楚这个插入语句做错了什么。我得到的错误是:

 "Failed processing format-parameters; %s" % err)
mysql.connector.errors.ProgrammingError: Failed processing format-parameters; 
'MySQLConverter' object has no attribute '_navigablestring_to_mysql'`

具体的代码行是:

update = '''INSERT INTO myDB.newtable (ID,Record,Latitude,Longitude,code) VALUES (%s,%s,%s,%s,%s)'''
cursor2.execute(update,(ID,Record,Latitude,Longitude,code))
cnx2.commit()

我也试过这种格式:

update = ("INSERT INTO myDB.newtable (ID,Record,Latitude,Longitude,code) VALUES (%s, %s, %s, %s, %s)")%(ID,Record,Latitude,Longitude,code)
cursor2.execute(update)

并得到这个错误: mysql.connector.errors.ProgrammingError:1054 (42S22):“字段列表”中的未知列“45676kb”

45676kb 只是整个值的一部分。完整的字符串是 45676kb-98734-98734-123nn

我认为第二次尝试的语法更正确,因为我至少遇到了一个 sql 错误,但我不知道如何使用 mysql.connector 正确格式化我的插入语句。

最佳答案

第一个选项是将查询参数放入查询的正确方法 - 它称为参数化查询。在这种情况下,您让数据库驱动程序转义查询参数,将它们安全地插入到查询中并处理 Python 到 MySQL 的类型转换。

您遇到的错误意味着它无法转换 IDRecordLatitudeLongitude 之一code> 或 code 参数值到有效的 MySQL 数据库类型。具体看你发的变量类型:

ID        <type 'unicode'> 
Record    <type 'unicode'>
Latitude  <class 'bs4.element.NavigableString'>
Longitude <class 'bs4.element.NavigableString'>
code      <type 'unicode'>

问题出在 LatitudeLongitude - 它们是 BeautifulSoupNavigableString类实例 - MySQL 转换器难以理解如何将 NavigableString 对象转换为有效的 MySQL 类型。事先明确地将它们转换为字符串:

update = """
    INSERT INTO 
        myDB.newtable 
        (ID,Record,Latitude,Longitude,code) 
    VALUES 
        (%s,%s,%s,%s,%s)
"""
cursor2.execute(update, (ID, Record, str(Latitude), str(Longitude), code))

关于python - 在 Python 中使用 mysql.connector 处理格式参数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36989671/

相关文章:

python - 如何使用自定义 IO 函数扩展 Pandas?

python - CMake 错误 : Unknown CMake command "ocv_glob_modules".“

php - Mysql 连接表有 2 个外键与同一个表

PHP 和 mySQL 单引号还是双引号?

.net - 我如何连接到 .NET 中的远程 mysql 服务器?

python - 在 PCAP 文件上使用 BPF

python - 在 VS Code 中,我不想让 Black 格式化我的 settings.json

python - 帮助使用 py2app 从 python 构建 mac 应用程序?

mysql在两台服务器(本地主机)不同端口之间复制数据

javascript - 如何从 Active Class 获取类别 ID 并传递给 Post 查询