mysql替换占位符_为什么不能在pymysql中用格式函数替换占位符?

bd96500e110b49cbb3cd949968f18be7.png

How i create the table mingyan.

CREATE TABLE `mingyan` (

`tag` varchar(10) DEFAULT NULL,

`cont` varchar(255) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

It's said that string format function with {} is more pythonic way than placeholder %.

In my scrapy to write some fields into a table mingyan.

self.cursor.execute("insert into mingyan(tag, cont) values (%s, %s)",(item['tag'],item['cont']))

It works fine in my scrapy,now i replace the placeholder way with string format function.

self.cursor.execute("insert into mingyan(tag, cont) values ({},{})".format(item['tag'],item['cont']))

The scrapy got error info

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax;

Why can't replace placeholder with format function in pymysql?

The item in scrapy doucment.

item meaning in scrapy

解决方案

In short: the parameter substitution implemented in cursor.execute is not the same as Python string formatting, despite the use of "%s" as a placeholder; that's why you get different results.

Databases expect query parameters to be quoted - surrounded by single or double quotes, even backticks - in specific ways. Python's DBAPI standard provides parameter substitution functionality to automate the tedious and error-prone process of parameter quoting.

Database driver packages that implement the DBAPI standard automatically apply the correct quoting rules to query parameters. So for example, given this code

cursor.execute("""INSERT INTO mytable (foo, bar) VALUES (%s, %s);""", ('bar', None))

The driver will generate sql with this VALUES clause:

VALUES ('bar', NULL)

Observe that

"bar" is in quotation marks

None has been converted to NULL, and left unquoted

Using string formatting rather than DBAPI parameter substitution means you need to know and apply these rules yourself, for example like this:

cursor.execute("""INSERT INTO mytable (foo) VALUES ('{}')""".format('bar'))

Note the quotation marks surrounding the format placeholder.

MySQL's quoting rules are discussed in detail in the answers to this question.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值