Python mysql显示语法错误

Python mysql显示语法错误,python,mysql,Python,Mysql,在python中执行此查询时遇到问题。我有一个IP数据库,它有3列startip、endip和country。现在我想知道ip的位置。这是我的密码 def get_country(ip): try: conn = MySQLConnection(host='localhost', database='ipdb', user ='root', password='password') cursor = conn.cursor()

在python中执行此查询时遇到问题。我有一个IP数据库,它有3列startip、endip和country。现在我想知道ip的位置。这是我的密码

def get_country(ip):

    try:
            conn = MySQLConnection(host='localhost', database='ipdb', user ='root', password='password')
            cursor = conn.cursor()
            query = 'SELECT * FROM db6 WHERE %s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
            ip_inint= ip2int(ip)
            cursor.execute(query,ip_inint)
            row = cursor.fetchone()
            while row is not None:
                    print " Start range %s end range %s country %s " %(row[0], row[1], row[2])
                    row = cursor.fetchone()
    except Error as error:
            print(error)
ip2int函数是

def ip2int(addr):
    return struct.unpack("!I", socket.inet_aton(addr))[0]
我收到的错误是

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 '%s BETWEEN INET_ATON(startip) AND INET_ATON(endip)' at line 1
有什么问题吗?

您需要将一个元组传递给
execute()

一份清单可能也会起作用:

cursor.execute(query, [ip_inint])
另一种方法是在查询中使用带有命名变量的字典:

query = 'SELECT * FROM db6 WHERE %(ip_inint)s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
cursor.execute(query, {'ip_inint': ip_inint})

参考:

缩进的%s是什么意思???这里的%s应该是什么意思?在那个位置,您需要一个列名或类似的名称?您还需要在表名周围加上反勾(`),在这一行游标中输入一个正在传递的ip地址。执行(查询,ip地址)不是我们应该如何将值传递给mysql的吗。就像他们所做的那样,我不明白你在说什么。请详细说明。(')缺失在哪里?我尝试了您的解决方案,但当我使用cursor.execute(查询,(ip输入,)或cursor.execute(查询,[ip输入])时,它显示“并非SQL语句中使用了所有参数”。最后一个解决方案奏效了。谢谢
query = 'SELECT * FROM db6 WHERE %(ip_inint)s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
cursor.execute(query, {'ip_inint': ip_inint})