python - 尝试将 ip 地址作为字符串插入 mysql 表时出现错误

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

我的代码有什么问题

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 视为字符串的 "":

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,) .

引号不是必需的。

关于python - 尝试将 ip 地址作为字符串插入 mysql 表时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130433/

相关文章:

python - scipy.optimize.basinhopping 不调用accept_test。为什么?

python - 简单问题 : In numpy how do you make a multidimensional array of arrays?

regex - Django AttributeError 'tuple'对象没有属性 'regex'

python-2.7 - 根据索引合并行

python - django没有名为article.models的模块

python - Flask - Jinja2 如何输出不同的 <div id/class>

mysql - 将 MySQL 函数的结果(在 WHERE 中使用)保留在我的查询结果中

mysqld : where is the query log file saved?

mysql - 使用mysql查询删除价格较低的重复产品

python - 无法导入名称 ProtocolError [RaspberryPi、Jasper]