1

I'm trying to run an INSERT query via a python program for thousands of records which have nullable fields as well. My requirement is such that the result set is transformed into key-value pairs in a dictionary and then parse the values into a list for executing INSERT query. However, when I try to add a NULL value to an int type field and execute INSERT via the program, I hit an error as shown below:

Warning: (1366, "Incorrect integer value: 'NULL' for column 'category_id' at row 1") result = self._query(query)

In the MySQL DB if I execute the query with 'NULL' or 'DEFAULT' keyword for the value of 'category_id', the value gets updated as NULL as expected.

Can someone please help zero in on what I'm missing here? Following is my code snippet:

    for s in result:
        temp_dict = {}
        for key, value in enumerate(s):
            if value is None:
                temp_dict[key] = pymysql.NULL
            else:
                temp_dict[key] = str(value)
5
  • 1
    share your table structure , one question category_id allow null? Commented Sep 24, 2018 at 12:18
  • 1
    @ZaynulAbadinTuhin Yes category_id is nullable. Commented Sep 24, 2018 at 12:20
  • 1
    could you please share your insert statement Commented Sep 24, 2018 at 12:24
  • @ZaynulAbadinTuhin The query formed by python looks something like 'INSERT INTO table_name VALUES ('a', 'b', .... 'NULL'). In this case the NULL field in the end happens to be of int type. Commented Sep 24, 2018 at 12:41
  • Possible duplicate of PyMySQL Insert NULL or a String Commented Sep 24, 2018 at 13:19

2 Answers 2

2

i think null is being converted to string as a result you got error could you try by passing the value None, not "NULL":

value = None
cursor.execute("INSERT INTO table (`column1`) VALUES (%s)", (value,))
Sign up to request clarification or add additional context in comments.

Comments

0

For a field expecting an Integer, MySQl replace a NULL field with 0 which should be the default value.

As you query you could use the IS NULL to single out the values with null values which you could then manipulate the value to an integer e.g 0

or you could tweek the query to only return values without a null at category_id by adding

WHERE category_id IS NOT NULL

SELECT * 
FROM table 
WHERE category_id IS NOT NULL

1 Comment

I'm trying to do a bulk insert here. I would want the code to be able to handle this for any NULL value irrespective of field type.

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.