1. id非自增表结构
CREATE TABLE `test_idms` (
`id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
;
2. id自增表结构
CREATE TABLE `test_idms_sub` (
`id` int NOT NULL AUTO_INCREMENT,
`sub_name` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
;
import log;
//1.1
body = {
"sub_name":"1.1测试自增insert"
}
var id = db.table("test_idms_sub").insert(body);
log.info("id1.1={}",id) //id1.1=19
//1.2
id = db.insert("insert into test_idms_sub(sub_name) values('1.2测试自增insert SQL')");
log.info("id1.2={}",id)
//1.3
body = {
"sub_name":"1.3测试自增Save插入"
}
id = db.table('test_idms_sub').primary('id').save(body);
log.info("id1.3={}",id)
//1.4
body = {
"sub_name":"1.4测试"
}
id = db.table("test_idms_sub").primary("id").insert(body);
log.info("id1.4={}",id)
总结:返回值是id;一般采用1.1的方式操作
2. 主键非自增
//2.1
body = {
"id":uuid(),
"name":"2.1测试非自增Insert"
}
id = db.table("test_idms").insert(body);
log.info("id2.1={}",id)
//2.2
body = {
"name":"2.2测试非自增Save/Insert"
}
id = db.table("test_idms").primary("id",uuid()).save(body);
log.info("id2.2={}",id)
//2.3
id = db.table("test_idms").primary("id",uuid()).insert(body);
log.info("id2.3={}",id)
//2.4
id = db.insert("insert into test_idms(id,name) values('" uuid() "','2.4测试非自增Insert SQL')");
log.info("id2.4={}",id)
总结:返回值null,获取不到id;一般采用2.1的方式操作
3. 批量插入
body=[
{
"id":uuid(),
"name":"3.1批量插入"
},
{
"id":uuid(),
"name":"3.2批量插入"
}
]
id = db.table("test_idms").batchInsert(body);
//返回的是插入的记录数
log.info("id3={}",id)
return id
Magic-Api对于数据库新增操作,非常简单,前端主要组装body结构提交即可,后端只需要几行代码解决。
,