1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonでMySQL触ってたらNULLがINSERTできなかった件

Posted at

mysqldbを使ってこんな文を作ってみた。

python
data1=1
data2=None
cursor.execute("INSERT INTO table1 VALUES ("+str(data1)+","+str(data2)+")")

Pythonで NULLはNoneらしい ので、こうしてみたものの、SQL的なエラーが発生する。

ポチポチググると、どうやらタプルで渡してやらないといけないらしい(謎)

How can I insert NULL data into MySQL database with Python?
https://stackoverflow.com/questions/5507948/how-can-i-insert-null-data-into-mysql-database-with-python

Python, Mysql, insert NULL
https://bytes.com/topic/python/answers/166025-python-mysql-insert-null

つまりこんな感じ

python
data1=1
data2=None
cursor.execute("INSERT INTO table1 VALUES (%s,%s)",(data1,data2))



ちなみに
INSERTする値が一つだけの時も、タプルとして渡さないといけないので、タプルである証として「,」をつけることになりますね。

python
data1=None
cursor.execute("INSERT INTO table1 VALUES (%s)",(data1,))
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?