Discuss / Python / 构造sql语句时为什么要用 `%s`而非%s呢?

构造sql语句时为什么要用 `%s`而非%s呢?

Topic source

郭子淳gzc

#1 Created at ... [Delete] [Delete and Lock User]

为什么在构造sql语句是要用%s,而不是%s,`起什么作用呢? 在创建table的时候也是,为什么用id`而不是id呢?

我编程的时候没有考虑``,测试find功能时没有问题,不过save就出现了错误,

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s,%s,%s,%s)' at line 1")

不过我把execute(sql, args)函数中的args改用tuple而非list就可以解决

下面是廖老师的程序:

create table users (
    `id` varchar(50) not null,
    `email` varchar(50) not null,
    `passwd` varchar(50) not null,
    `admin` bool not null,
    `name` varchar(50) not null,
    `image` varchar(500) not null,
    `created_at` real not null,
    unique key `idx_email` (`email`),
    key `idx_created_at` (`created_at`),
    primary key (`id`)
) engine=innodb default charset=utf8;在此插入代码


attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1))

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

因为sql有很多关键字,如果表名、列名和关键字重名,就必须用` 括起来

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

mysql用` ,其他有用[]的,还有用别的的

郭子淳gzc

#4 Created at ... [Delete] [Delete and Lock User]

好的,明白了,谢谢廖老师解答!


  • 1

Reply