How can I insert NULL data into MySQL database with Python?

后端 未结 4 1743
北荒
北荒 2020-12-03 00:16

I\'m getting a weird error when inserting some data from a Python script to MySQL. It\'s basically related to a variable being blank that I am inserting. I take it that MyS

相关标签:
4条回答
  • 2020-12-03 01:11

    Why not set the variable equal to some string like 'no price' and then filter this out later when you want to do math on the numbers?

    filter(lambda x: x != 'no price',list_of_data_from_database)
    
    0 讨论(0)
  • 2020-12-03 01:13

    if the col1 is char, col2 is int, a trick could be:

    insert into table (col1, col2) values (%s, %s) % ("'{}'".format(val1) if val1 else "NULL", val2 if val2 else "NULL");
    

    you do not need to add ' ' to %s, it could be processed before pass value to sql.

    this method works when execute sql with session of sqlalchemy, for example session.execute(text(sql))

    ps: sql is not tested yet

    0 讨论(0)
  • 2020-12-03 01:15

    When using mysqldb and cursor.execute(), pass the value None, not "NULL":

    value = None
    cursor.execute("INSERT INTO table (`column1`) VALUES (%s)", (value,))
    

    Found the answer here

    0 讨论(0)
  • 2020-12-03 01:18

    Do a quick check for blank, and if it is, set it equal to NULL:

    if(!variable_to_insert)
        variable_to_insert = "NULL"
    

    ...then make sure that the inserted variable is not in quotes for the insert statement, like:

    insert = "INSERT INTO table (var) VALUES (%s)" % (variable_to_insert)
    ...
    

    not like:

    insert = "INSERT INTO table (var) VALUES ('%s')" % (variable_to_insert)
    ...
    
    0 讨论(0)
提交回复
热议问题