1

I'm having issues with python when I try to insert NULL into a field using a prepared mysqldb statement. The problem is that python doesn't like NULL without quotes and then MySQL doesn't like 'NULL' with quotes; so I'm trying to find a way to insert NULL that both, python and MySQL, will allow. Here is my scenario:

    sqlFailInsert = """INSERT INTO efix_headers ( PathID ) VALUES ( %s );"""
    //then later in my code
    failcur = self.db.query( self.sqlFailInsert, ( pathID if pathID else NULL ) )

This generates a python error of: global name 'NULL' is not defined but when I use: pathID if pathID else 'NULL' MySQL treats it as a string (by the way, pathID field is an integer field) and enters 0 for the value (as it should if you were entering a string into an int field).

So, my questions is, how can I insert NULL into the int field using a prepared statement and not violate python rules?

1 Answer 1

7

Use None instead of NULL

sqlFailInsert = """INSERT INTO efix_headers ( PathID ) VALUES ( %s );"""
//then later in my code
failcur = self.db.query( self.sqlFailInsert, ( pathID if pathID else None ) )
Sign up to request clarification or add additional context in comments.

2 Comments

And MySQL will evaluate 'None' to NULL automatically?
Yes. "SQL NULL values are represented by the Python None singleton on input and output". More information at: python.org/dev/peps/pep-0249

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.