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

ada*_*dam 5 python mysql

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

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

具体的代码行是:

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()
Run Code Online (Sandbox Code Playgroud)

我也试过这种格式:

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

并收到此错误: mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column '45676kb' in 'field list'

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

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

ale*_*cxe 5

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

错误您收到意味着它不能转换的一个IDRecordLatitudeLongitudecode参数值到一个有效的MySQL数据库类型。具体来说,请参阅您发布的变量类型:

ID        <type 'unicode'> 
Record    <type 'unicode'>
Latitude  <class 'bs4.element.NavigableString'>
Longitude <class 'bs4.element.NavigableString'>
code      <type 'unicode'>
Run Code Online (Sandbox Code Playgroud)

问题在于Latitudeand Longitude- 它们是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))
Run Code Online (Sandbox Code Playgroud)