Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrecognized token in SQLite statement

I am inserting data from one table to another, however for some reason I get "unrecognized token". This is the code:

cur.execute("INSERT INTO db.{table} SELECT distinct latitude, longitude, port FROM MessageType1 WHERE latitude>={minlat} AND latitude<={maxlat} AND longitude>= {minlong} AND longitude<= {maxlong}".format(minlat = bottomlat, maxlat = toplat, minlong = bottomlong, maxlong = toplong, table=tablename))

This translates to the following, with values:

INSERT INTO db.Vardo SELECT distinct latitude, longitude, port FROM MessageType1 WHERE latitude>=69.41 AND latitude<=70.948 AND longitude>= 27.72 AND longitude<= 28.416

The error code is the following:

sqlite3.OperationalError: unrecognized token: "70.948 AND"

Is the problem that there is three decimal points?

This is the create statement for the table:

cur.execute("CREATE TABLE {site} (latitude, longitude, port)".format(site = site))
like image 610
bjornasm Avatar asked Apr 15 '26 16:04

bjornasm


2 Answers

Don't make your SQL queries via string formatting, use the driver's ability to prepare SQL queries and pass parameters into the query - this way you would avoid SQL injections and it would make handling of passing parameters of different types transparent:

query = """
    INSERT INTO 
        db.{table} 
    SELECT DISTINCT
        latitude, longitude, port 
    FROM 
        MessageType1 
    WHERE 
        latitude >= ? AND 
        latitude <= ? AND 
        longitude >= ? AND 
        longitude <= ?
""".format(table=tablename)
cur.execute(query, (bottomlat, toplat, bottomlong, toplong))
like image 83
alecxe Avatar answered Apr 18 '26 07:04

alecxe


Try using ? for your parameters:

cur.execute("INSERT INTO db.? SELECT distinct latitude, longitude, port FROM MessageType1 WHERE latitude>=? AND latitude<=? AND longitude>= ? AND longitude<= ?",(bottomlat, toplat, bottomlong, toplong, tablename))
like image 37
Sam cd Avatar answered Apr 18 '26 06:04

Sam cd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!