我在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
可能是什么问题?
答案 0 :(得分:1)
您需要将元组传递给execute()
:
cursor.execute(query, (ip_inint,))
列表也可能有效:
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})
参考:http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html