简体   繁体   中英

mysql is showing error in the syntax

I am having trouble in executing this query in python. I have an IP database which has 3 column startip, endip and country. Now I want to the location of the ip. this is my code

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 function is

def ip2int(addr):
    return struct.unpack("!I", socket.inet_aton(addr))[0]

error i am receiving is

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

what could be the issue?

You need to pass a tuple to execute() :

cursor.execute(query, (ip_inint,))

A list will probably work too:

cursor.execute(query, [ip_inint])

An alternative is to use a dictionary with named variables in the query:

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

Reference: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM