将ip地址插入mysql时出错

drkbr07n  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(393)

我试过很多次用不同的代码在mysql int unsigned字段中插入一个ip地址,任何指针都可以,我看过google上的所有例子,没有任何帮助
这是我的密码

  1. icecast_source_ip = "INET_ATON('" + icecast_source_ip +"')"
  2. print icecast_source_ip
  3. cnx = mysql.connector.connect(host=mysql_remote_host,
  4. user=mysql_remote_host_user,
  5. password=mysql_remote_host_password,
  6. database=mysql_remote_host_database)
  7. cursor = cnx.cursor()
  8. cursor.execute("INSERT INTO icecast_monitor.status_log
  9. (website_online, icecast_source_online, icecast_source_ip,
  10. icecast_no_listeners, centerpoint_online, centerpoint_connection,
  11. horsleypark_online, horsleypark_connection, system_ok)
  12. VALUES ('" + website_online + "','"
  13. + icecast_source_online + "','"
  14. + icecast_source_ip + "','"
  15. + icecast_no_listeners + "','"
  16. + centerpoint_online + "','"
  17. + centerpoint_connection + "','"
  18. + horsleypark_online + "','"
  19. + horsleypark_connection + "','"
  20. + system_ok + "')
  21. ")
  22. print 'Data inserted into Database'
  23. cnx.commit()
  24. cursor.close()
  25. cnx.close()

我得到的错误
意外错误1064(42000):您的sql语法有错误;在第1行的“60.241.175.9”)、“19”、“true”、“main”、“true”、“main”、“false”)附近,检查与您的mysql服务器版本对应的手册中使用的正确语法

6ljaweal

6ljaweal1#

问题在于变量的值 icecast_source_ip .
在soure ip value变量周围已经有了单引号。

  1. icecast_source_ip = "INET_ATON('" + icecast_source_ip +"')"

但是在查询中使用它时,您再次用引号将生成的字符串括起来。结果查询如下所示:

  1. // + "','" + icecast_source_ip + "','"
  2. + "','"+ INET_ATON(' + 60.241.175.9 + ') + "','"

为了可读性,字符串替换如下所示:

  1. + "','INET_ATON('60.241.175.9')','"

因此实际的ip地址值 60.241.175.9 缺少引号,sql引擎试图将其识别为标识符,但失败,因为格式错误,因此出现语法错误。
请用事先准备好的发言来克服这些问题。

展开查看全部
1dkrff03

1dkrff032#

如注解中所述,您没有引用这些值,因此像ip地址这样的字符串在最终sql查询中没有所需的单引号。
正确且安全的方法是使用参数化查询。您不必担心引用,也不必担心在使用字符串操作手动构造查询字符串时可能出现的sql注入漏洞。例如,您可以这样做:

  1. query = """INSERT INTO icecast_monitor.status_log
  2. (website_online, icecast_source_online, icecast_source_ip,
  3. icecast_no_listeners, centerpoint_online, centerpoint_connection,
  4. horsleypark_online, horsleypark_connection, system_ok)
  5. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"""
  6. cursor.execute(query, (website_online, icecast_source_online, icecast_source_ip, icecast_no_listeners, centerpoint_online, centerpoint_connection, horsleypark_online, horsleypark_connection, system_ok))

这将使用占位符 %s 以指示参数应插入的位置,然后 cursor.excute() 将第二个参数中带有正确引号的参数插入到查询中,然后将其发送执行。

相关问题