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

后端 未结 4 1747
北荒
北荒 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: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

提交回复
热议问题