node-mysql中占位符?的使用

要mysql执行的命令串如果是固定的,那么不需要使用占位符,如果其中的一些参数允许在执行前可自由设定,那么使用占位符就很必要,这样你可以不需要由自己来拼接出一个完整的执行串,只需要在执行串模板上将占位符的参数设置成需要的值就可以了,由node-mysql来完成最终执行串的生成。

sql 复制代码
let sqlstr='select studentname from table where score >= ? and score <= ? '
connect.query(sqlstr,[85,100])

占位符??用于替换表名和字段名,占位符?用于替换字段值,注意了,每个占位符与你传入的参数要一一对应。

sql 复制代码
let sqlstr='select studentname from table where ?? >= ? and score <= ? '
connect.query(sqlstr,["score",85,100])

批量插入场景就最适合用占位符了。

sql 复制代码
let sqlstr='insert into table(studentname,gender,score) values ? '
indata=[
["张三","男",98],
["李四","女",95]
]
connect.query(sqlstr,[indata])

如果表比较宽,字段太多,写在模板串里太长,怕出错怎么办?这个自己把模板串拼接下:

javascript 复制代码
let fileds=["f1","f2","f3","f4","f5","f6","f7","f8"];
let sqlcmd='insert into a('+fileds.join()+') values ?'

就插入一条记录,但是values来自几个不同的源,比如f1,f2来自item1,f3,f4,f5来自item2,f6,f7,f8来自item3,有简单的插入办法么?好办!

sql 复制代码
let fileds=["f1","f2","f3","f4","f5","f6","f7","f8"];
let sqlcmd='insert into a('+fileds.join()+') values (?,?,?)'
let item1=[1,2]
let item2=[3,4,5]
let item3=[6,7,8]
connect.query(sqlstr,[item1,item2,item3])

mysql.format是个好的测试工具,如果对字符串的书写不放心,没有把握,可以先在本地输出下mysql.format结果,不必直接发到mysql的DB上去执行检验。

javascript 复制代码
const mysql = require("mysql"); 
let fileds=["f1","f2","f3","f4","f5","f6","f7","f8"];
let sqlcmd='insert into a('+fileds.join()+') values (?,?,?)'
let indata=[[1,2],[3,4,5],[6,7,8]]
console.log(mysql.format(sqlcmd,indata))
//输出 insert into a(f1,f2,f3,f4,f5,f6,f7,f8) values (1, 2,3, 4, 5,6, 7, 8)
相关推荐
星辰徐哥5 小时前
Spring Boot 微服务架构设计与实现
spring boot·后端·微服务
星辰徐哥5 小时前
Spring Boot 数据导入导出与报表生成
spring boot·后端·ui
明夜之约5 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee5 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Micro麦可乐5 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
Jinkxs5 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
毕设源码_郑学姐5 小时前
计算机毕业设计springboot网络相册设计与实现 基于Spring Boot框架的在线相册管理系统开发与应用 Spring Boot驱动的网络影集设计与实践
spring boot·后端·课程设计
辣机小司5 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
码农阿豪5 小时前
从零到一:Spring Boot快速接入金仓数据库实战
数据库·spring boot·后端
追逐时光者6 小时前
一个基于 .NET 与 Avalonia 构建、面向 TrinityCore 的开源 WoW 数据库编辑器
后端·.net