将IP地址插入mysq时出错

2024-09-30 16:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过很多次用不同的代码在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


Tags: iphostsourceremotemysqlpasswordconnectioncursor
2条回答

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

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

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

^{pr2}$

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

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

因此,实际的ip地址值60.241.175.9没有引号,sql引擎试图将其识别为标识符,但由于格式错误而失败,因此是语法错误。在

请使用事先准备好的陈述来克服这些问题。在

如注释中所述,您没有引用这些值,因此在最终的SQL查询中,诸如IP地址之类的字符串没有所需的单引号。在

正确且安全的方法是使用参数化查询。您不必担心引用,也不必担心在使用字符串操作手动构造查询字符串时可能出现的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, %s, %s, %s, %s, %s, %s, %s)"""

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()将第二个参数中的参数和正确的引号插入到查询中,然后发送查询执行。在

相关问题 更多 >