我试过很多次用不同的代码在mysql int unsigned字段中插入一个ip地址,任何指针都可以,我看过google上所有的例子,没有任何帮助
这是我的密码
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()
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()
以及我所犯的错误
Unexpected error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '60.241.175.9')','19','True','Main','True','Main','False')' at line 1
变量
icecast_source_ip
的值有问题。在soure ip value变量周围已经有了单引号。在
但是在查询中使用它时,您再次用引号将生成的字符串括起来。结果查询如下所示:
^{pr2}$为了可读性,字符串替换如下所示:
因此,实际的ip地址值
60.241.175.9
没有引号,sql引擎试图将其识别为标识符,但由于格式错误而失败,因此是语法错误。在请使用事先准备好的陈述来克服这些问题。在
如注释中所述,您没有引用这些值,因此在最终的SQL查询中,诸如IP地址之类的字符串没有所需的单引号。在
正确且安全的方法是使用参数化查询。您不必担心引用,也不必担心在使用字符串操作手动构造查询字符串时可能出现的SQL注入漏洞。对于您的示例,您可以这样做:
它使用占位符
%s
来指示参数应该插入的位置,然后cursor.excute()
将第二个参数中的参数和正确的引号插入到查询中,然后发送查询执行。在相关问题 更多 >
编程相关推荐