You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL INT UNSIGNED字段插入IP地址报1064错误,求解决指引

解决MySQL插入IP到INT UNSIGNED字段的语法错误问题

看起来你踩了字符串拼接SQL的典型坑——把INET_ATON()函数调用当成普通字符串处理了,导致MySQL解析SQL时出现语法错误。咱们一步步拆解问题和解决办法:

问题根源

你的代码里先把icecast_source_ip处理成了"INET_ATON('60.241.175.9')",然后在拼接INSERT语句时,又给这个字符串套了一层单引号,最终SQL里的对应部分变成了:

'INET_ATON('60.241.175.9')'

这就乱套了:第一个单引号开启字符串,到('里的单引号就提前结束了,后面的60.241.175.9')完全不符合SQL语法,所以才会报1064错误。

解决办法

1. 使用参数化查询(强烈推荐)

这是处理数据库操作的最佳实践,既能避免语法错误,还能彻底防止SQL注入。把INET_ATON()直接写在SQL模板里,IP地址作为参数传递:

# 删掉这行错误的处理代码:icecast_source_ip = "INET_ATON('" + icecast_source_ip +"')"

# 建立数据库连接
cnx = mysql.connector.connect(host=mysql_remote_host, user=mysql_remote_host_user, password=mysql_remote_host_password, database=mysql_remote_host_database)
cursor = cnx.cursor()

# 定义带占位符的SQL语句,INET_ATON()直接写在语句中
sql_query = """
INSERT INTO icecast_monitor.status_log 
(website_online, icecast_source_online, icecast_source_ip, icecast_no_listeners, centerpoint_online, centerpoint_connection, horsleypark_online, horsleypark_connection, system_ok) 
VALUES (%s, %s, INET_ATON(%s), %s, %s, %s, %s, %s, %s)
"""

# 准备参数列表,按顺序对应占位符
query_params = (
    website_online, 
    icecast_source_online, 
    icecast_source_ip, 
    icecast_no_listeners, 
    centerpoint_online, 
    centerpoint_connection, 
    horsleypark_online, 
    horsleypark_connection, 
    system_ok
)

# 执行参数化查询
cursor.execute(sql_query, query_params)

print('Data inserted into Database')
cnx.commit()
cursor.close()
cnx.close()

2. 修复字符串拼接(不推荐,存在风险)

如果你暂时不想改参数化,也可以调整拼接逻辑——去掉icecast_source_ip外层的单引号,因为函数调用不需要被引号包裹:

# 保留这行处理,但注意后续拼接时不要加单引号
icecast_source_ip = "INET_ATON('" + icecast_source_ip +"')"
print(icecast_source_ip)

cnx = mysql.connector.connect(host=mysql_remote_host, user=mysql_remote_host_user, password=mysql_remote_host_password, database=mysql_remote_host_database)
cursor = cnx.cursor()

# 关键修改:icecast_source_ip前后不要加单引号
cursor.execute("INSERT INTO icecast_monitor.status_log (website_online, icecast_source_online, icecast_source_ip, icecast_no_listeners, centerpoint_online, centerpoint_connection, horsleypark_online, horsleypark_connection, system_ok) VALUES ('" + website_online + "','" + icecast_source_online + "'," + icecast_source_ip + ",'" + icecast_no_listeners + "','" + centerpoint_online + "','" + centerpoint_connection + "','" + horsleypark_online + "','" + horsleypark_connection + "','" + system_ok + "') ")

print('Data inserted into Database')
cnx.commit()
cursor.close()
cnx.close()

重要提醒

永远优先选择参数化查询,字符串拼接不仅容易出语法问题,还会让你的代码暴露在SQL注入攻击的风险下,这是数据库操作的大忌。

内容的提问来源于stack exchange,提问作者Ossama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:15:19