【问题标题】:Getting error trying to insert ip address as string in mysql table尝试将 ip 地址作为字符串插入 mysql 表中时出错
【发布时间】:2020-03-26 13:33:36
【问题描述】:

我的代码有什么问题,

with connect_db() as conn:
    cursor = conn.cursor()
    stmt = """INSERT INTO ip_records ip_address VALUES (%s)"""
    try:
        cursor.execute(stmt, (ip))
    except mysql.connector.Error as err:
        print err
        return 

我正在尝试将 ip 地址作为字符串插入 mysql 表。但是我收到了这个错误:

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ip_address VALUES (192.168.11.111)' at line 1

【问题讨论】:

  • 应该是(ip_address)

标签: python mysql python-2.7 mysql-connector-python insert-statement


【解决方案1】:

您缺少 "" 以将 IP 视为字符串:

with connect_db() as conn:
    cursor = conn.cursor()
    stmt = """INSERT INTO ip_records (ip_address) VALUES (%s)"""
    try:
        cursor.execute(stmt, (ip,))
    except mysql.connector.Error as err:
        print err
        return 

编辑 你还需要一个逗号来作为元组传递参数(ip,)而不是(ip)

实际的错误是语法错误((ip_address) 周围没有括号,而 (ip,) 元组上没有逗号导致 python 参数错误。

引号不是必需的。

【讨论】:

  • 然后我得到错误:ValueError: Could not process parameters
  • 还包括括号
  • 括号内的ip 后面需要一个逗号 > cursor.execute(stmt, (ip,))
  • 您不需要在参数标记周围的 SQL 中使用引号。
【解决方案2】:

ip_address 周围的You need to add 括号或删除它。

【讨论】:

  • 然后我得到错误:ValueError: Could not process parameters
  • 我假设更进一步。 ip_address的数据类型是怎么定义的,插入了什么值?
  • 我在询问数据库架构。
  • ip_address是mysql db中的字符串类型。
猜你喜欢
  • 2011-01-12
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
相关资源
最近更新 更多