带变量的SQL语句操作

# 带变量的SQL查询语句
# 01

select_userMobile = "select * from tt_user_index where user_mobile= '{}';".format(whiteUserMobile)
select_userMobile = "select * from tt_user_index where user_mobile= '%s';"%(whiteUserMobile)


#01插入语句,通过使用变量插入值
 strSQL = "INSERT INTO info(firstname,lastname,sex,age) VALUES('"&rfname&"','"&rlname&"','"&rsex&"',"&rage&")"

 或
 strSQL = "INSERT INTO info(firstname,lastname,sex,age) VALUES('"+rfname+"','"+rlname+"','"+rsex+"',"+rage+")" 

说明:
如果传入的是字符型请在变量处使用(外单引号,内双引号)'"&变量&"'这种格式,如果传是数值型的可以直接用(只有双引号)"&变量&"


# 02
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
       ('Mac', 'Mohan', 20, 'M', 2000)
在使用pymysql的executemany方法时,需要注意的几个问题

1、在写sql语句时,不管字段为什么类型,占位符统一使用%s,且不能加上引号。例如

sql="insert into tablename (id,name) values (%s,%s)"

2、添加的数据的格式必须为list[tuple(),tuple(),tuple()]或者tuple(tuple(),tuple(),tuple())例如

values=[(1,"zhangsan")],(2,"lisi")]
#或者
values=((1,"zhangsan")],(2,"lisi"))

最后,通过executemany插入

cursor.executemany(sql,values) 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。