Search code examples
pythonmysqlsql-insertindentationmysql-python

How to do an insert in the database with Python


I have a Python script that does the Moodle version check. After checking the Moodle version I would like to insert into the database but I am getting the following error:

line 337
mycursor = db.cursor()
TabError: inconsistent use of tabs and spaces in indentation

This is the code that using and with problems:

import import mysql.connector

...

def printversion(version):
if version != 0:
    print ("\nVersion found via " + version.split(';')[2] + " : Moodle " +  version.split(';')[0])
    vuln = version.split(';')[0]
    db = mysql.connector.connect(host="localhost", user="admin", passwd="", database="test")
    mycursor = db.cursor() 
    insertQuery = """INSERT INTO moodle (id,payload) VALUES (%s,%s)"""
    mycursor.execute(insertQuery, ('',vuln))
    db.commit()  
    db.close()
    return version.split(';')[0].replace("v","")
    
print ("\nVersion not found")
return False

The error reported is about code indentation, but I don't know how to solve this problem to insert versioning results in the database.

Is code with indentation:

enter image description here


Solution

  • You have a slight misunderstanding here, in any function in python you need to provide an indentation(tab) before you start writing any code,

    i.e. structure is

    def your_functionname(parameters)
        < you code here >
    

    So, in a correct way, your code should look like this

    ...
    
    def printversion(version):
        if version != 0:
            print ("\nVersion found via " + version.split(';')[2] + " : Moodle " +  
            version.split(';')[0])
            vuln = version.split(';')[0]
            db = mysql.connector.connect(host="localhost", user="admin", passwd="", 
            database="test")
            mycursor = db.cursor() 
            insertQuery = """INSERT INTO moodle (id,payload) VALUES (%s,%s)"""
            mycursor.execute(insertQuery, ('',vuln))
            db.commit()  
            db.close()
            return version.split(';')[0].replace("v","")
            
        print ("\nVersion not found")
        return False