Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

mysql

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 MySQL does not like blank variables but is there something else I can change it to so it works with my insert statement?

I can successfully use an IF statement to turn it to 0 if its blank but this may mess up some of the data analytics I plan to do in MySQL later. Is there a way to convert it to NULL or something so MySQL accepts it but doesn't add anything?

like image 869
Lostsoul Avatar asked Apr 01 '11 00:04

Lostsoul


People also ask

Can we insert NULL in MySQL?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL); To understand the above syntax, let us first create a table.

How can I insert NULL values SQL?

You also can specify the NULL keyword in the VALUES clause to indicate that a column should be assigned a NULL value. The following example inserts values into three columns of the orders table: INSERT INTO orders (orders_num, order_date, customer_num) VALUES (0, NULL, 123);

How do I insert a NULL in MySQL workbench?

You can right-click on a cell and choose "Clear Field Content" in the popup menu. It will set the cell value to NULL.


2 Answers

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

like image 141
j c Avatar answered Sep 22 '22 03:09

j c


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

like image 33
buxizhizhoum Avatar answered Sep 26 '22 03:09

buxizhizhoum