如何将 Null/None 输入 mysql

How can I enter Null/None into mysql

我正在使用 Python 3.7 和 pyMySQL 作为 MySQL 服务器的连接器。

我正在尝试执行以下查询:

query="INSERT IGNORE INTO  tweets (ID, Text,create," \
                    "Date,local,foolowed,Count," \
                    "isqwdii,inR,in " \
                    "Sensitive,redirection)" \
                    "VALUES (%s,%s,%s,%s,%s,%d,%d,%d,%s,%s,%d,%d)"
vals=[kwargs['ID'], kwargs['Text'],
                   kwargs['create'], kwargs['Date'],
                   kwargs['local'], kwargs['foolowed'],
                   kwargs['Count'], kwargs['isascii'],
                   kwargs['inR'], kwargs['in'],
                   kwargs['Sensitive'], kwargs['redirection']] 
self.__cur.execute(query,vals)
self.__conn.commit()

问题是部分 %d 可能是 None,当它发生时我得到以下错误 "TypeError: %d format: a number is required, not str"。

我不能使用该格式,因为它会使 get None 作为数据库中的字符串。我希望数据库将其作为 None/NULL

提前致谢

我认为您需要测试 Python 代码中是否为 NULL,如果是,请将 %d 替换为 %s 以获得 字符串.

(我在 PHP 中的经验是 Null 是一个字符串类型,所以我假设这是传递给 Python MySQL 接口)

因此 pseudo-code 将是:

>>>    type['isascii'] = '%d'
>>>    if kwargs['isascii'] is None:
>>>        type['isascii'] = '%s'

>>>>   query= "INSERT IGNORE INTO  tweets (ID, Text,create," \
                "Date,local,foolowed,Count," \
                "isqwdii,inR,in " \
                "Sensitive,redirection)" \
                f"VALUES (%s,%s,%s,%s,%s,%d,%d,{str(type['isascii'])},%s,%s,%d,%d)"

我很抱歉,因为我不知道 Python 3.7 语法,但我希望这能给你概念。

Leo120 的回复:

Actually it worked when I placed all placeholders as %s (and got all the data as needed in the MySQL). as it turns out, in the pymysql %s stands for all, wierd. thank you for your help