尝试将 ip 地址作为字符串插入 mysql table 时出错

Getting error trying to insert ip address as string in mysql table

我的代码有什么问题,

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 table。但我收到此错误:

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

You need to add 括号 ip_address 或将其删除。

您缺少 "" 以将 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) 周围没有方括号,python 参数错误是因为元组 (ip,) 上没有逗号。

引号不是必需的。