Search code examples
pythonmysql-pythonstrip

How to trim white space in MySQLdb using python


I have a web form taking user data and putting it into a mysql database. I need to trim leading and trailing blanks/spaces. I currently am utilizing the strip() method, but it only trims them for the fields, NOT for the mysql database.

My code is:

first_name = first_name.strip()
last_name = last_name.strip()

so on and so forth. It strips it perfectly fine for the webpage, but not when it is entered into the SQL database. The spaces still exist. How do I remove them?

EDIT:

        db = MySQLdb.connect("localhost","user","pass","db_name")
        cursor = db.cursor()
                cursor.execute("Select * FROM registrants")
                cursor.execute("INSERT INTO registrants VALUES( " + "'" + first_name + "'" + ", " + "'" + last_name + "'" + ");")
        db.commit()
        db.close()

Solution

  • It could be a scope issue.

    If the stripping occurs in a different scope (ex: first_name is a global variable and the strip() occurs in a function) then you will not benefit from it in another scope (if the insert is happening in another function for example).

    Have you tried this for a test:

    cursor.execute("INSERT INTO registrants VALUES( " + "'" + first_name.strip() + "'" + ", " + "'" + last_name.strip() + "'" + ");")
    

    btw, how do you know there's a space in the db? There could be an issue with the way the data is retrieved or displayed..