简体   繁体   中英

Python mysql.connector error while inserting boolean into mysql database

In the code below, I am trying to insert a boolean value in Network table, where the status field is declared as boolean.

import urllib2
import mysql.connector as conn
import MySQLdb
import logging

class getData:

    @staticmethod   
    def checkNetwork():
        try:
            urllib2.urlopen('https://www.google.com', timeout = 2)
            return True
        except urllib2.URLError as err:
            return False

    @staticmethod
    def connectDB():
        db = conn.connect(host='****', user='****', passwd='****', db='*******')
        cursor = db.cursor()
        return db,cursor

    @staticmethod
    def insertNData(data):
        print type(data)
        db,cursor = getData.connectDB()
        sql_Query = "INSERT INTO Network(status) VALUES(%s);"
        try:
            result= cursor.execute(sql_Query,data)
            db.commit()
            logging.warn("%s", result)
            logging.info("Success")
        except MySQLdb.IntegrityError:
            logging.warn("Failed")
        finally:
            db.close()
        return True


netStat = getData.checkNetwork()

getData.insertNData(netStat)

When I run the code, I get the below error

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 '%s)' at line 1

I tried searching on google to find some solution and also changed a few things to test but still the same error.

Thanks in advance.

There is error in this line:

sql_Query = "INSERT INTO Network(status) VALUES(%s);"

You are not passing the value correctly. You created a placeholder but did not fill it.

Use:

for python3.6 and above:

sql_Query = f"INSERT INTO Network(status) VALUES({data});"

for python 2 and 3:

sql_Query = "INSERT INTO Network(status) VALUES({});".format(data)

or

sql_Query = "INSERT INTO Network(status) VALUES(%s);" %(data)

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