1. 程式人生 > >Python 在mysql資料庫中插入空值

Python 在mysql資料庫中插入空值

Python中沒有NULL,只有None,操作mysql資料庫時,當某個值為空,不能使用下列插入語句

# 錯誤案例
a = None
cursor = db.cursor()
sql = "INSERT INTO 表名 VALUES ('%s')" % a
cursor.execute(sql)
db.commit()

應該使用下列這種方式操作

# 正確案例
a = None
cursor = db.cursor()
sql = "INSERT INTO 表名 VALUES (%s)"
par = a
cursor.execute(sql, par)
db.commit()

注意兩個佔位符,一個有引號,一個沒引號!!!!!
如果有錯誤, 歡迎指出, 有更好的做法,給我留言