PyMySQL插入NULL或字符串 [英] PyMySQL Insert NULL or a String

查看:397
本文介绍了PyMySQL插入NULL或字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用PyMySQL插入一个字段(title),该字段可以是NULL或字符串.但这不起作用.

I tried to insert a field (title) with PyMySQL that can be NULL or a string. But it doesn't work.

query = """
    INSERT INTO `chapter` (title, chapter, volume)
    VALUES ("%s", "%s", %d)
"""

cur.execute(query % (None, "001", 1))
cur.execute(query % ("Title", "001", 1))

此代码将None插入数据库.如果删除第一个%s周围的双引号,则会引发错误:

This code inserts None into the database. If I remove the double quote around the first %s, it throws an error:

pymysql.err.InternalError: (1054, "Unknown column 'None' in 'field list'")

如何插入NULL?

推荐答案

1)切勿对SQL使用字符串格式.

1) Never use string formatting for SQL.

2)尝试以下操作:

query = """
INSERT INTO `chapter` (title, chapter, volume)
VALUES (%s, %s, %s)
"""
cur.execute(query, (None, "001", 1))

这篇关于PyMySQL插入NULL或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆