用户:
AbnormalLOG查看:6 回复:21 评论:6 创建时间:2021-09-21T12:40:31
这是我的第一个教程贴,
写的不好,将就看看吧(
祝大家中秋节快乐!
----------------------------------------------------------------------------------
1.db.sql
db.sql这个语句在box3中是用来执行SQL代码的,
我们所有的SQL代码都要放在这里执行.
比如:
db.sql`SELCT * FROM playerdata`
2.创建表格
创建表格用的是 CREATE TABLE,如下:
db.sql`CREATE TABLE IF NOT EXISTS playerdata (
score INT NOT NULL, --分数,NOT NULL的意思是不可以为空,INT指的是整数类型
id CHAR(16) NOT NULL --玩家userKey,类型是CHAR,最大长度是16
)`
这段代码中创建了一个表格,叫playerdata,
其中有两个字段,
都不可以为空.
3.查找数据
查找数据使用的是SELECT
如下:
world.onPlayerJoin(async({entity})=>{
entity.score=0
if (entity.player.userKey!="") {
var data = await db.sql`SELECT * FROM playerdata WHERE id = ${entity.player.userKey}`//查找playerdata这个表格中id是这个玩家的userKey的数据
if (data && !data.length) {
db.sql`INSERT INTO playerdata (
score,
id
) VALUES (
${entity.score},
${entity.player.userKey}
)`//插入数据到表格,等一下会讲
} else {
entity.score = data[0].score//把资料里上次存档的数据变成当前的数据,存档就完成了
}
}
})
4.插入数据
插入数据使用INSERT INTO,如下:
db.sql`INSERT INTO playerdata ( --playerdata是表格的名字
score, --对应的字段
id
) Values (
0, --对应的值
'dfhjshbfgdfjk'
)`
代码将会插入一个新数据,score是0,id是'dfhjshbfgdfjk'.
5.改变数据
如果想改变某个数据,使用Update
如下:
db.sql`UPDATE plauerdata SET score = 123 WHERE id = 'eioufhbskjdfhk'`
/*
将playerdata这个表格中id为eioufhbskjdfhk的数据的score值改成123,
通常用在保存.
*/
最后,再送大家一套完整的SQL基础代码:
db.sql`CREATE TABLE IF NOT EXISTS playerdata (
score INT NOT NULL,
id CHAR(16) NOT NULL
)`
world.onPlayerJoin(async ({ entity }) => {
entity.score = 0
entity.player.canFly = true
entity.enableDamage = true
if (entity.player.userKey != "") {
var data = await db.sql`SELECT * FROM playerdata WHERE id = ${entity.player.userKey}`
if (data && !data.length) {
db.sql`INSERT INTO playerdata (
score,
id
) VALUES (
${entity.score},
${entity.player.userKey}
)`
} else {
entity.score = data[0].score
}
}
})
world.onPress(async ({ entity, button }) => {
if (button == Box3ButtonType.ACTION1) {
var d1 = await select(entity, ["保存"], `你当前得分:${entity.score}`)
if (d1 == "保存") {
if (entity.player.userKey != "") {
db.sql`UPDATE playerdata SET score = ${entity.score} WHERE id = ${entity.player.userKey}`
text(entity, "保存完成")
} else {
text(entity, "请先登录哦")
}
}
}
})
world.onPlayerLeave(({ entity }) => {
if (entity.player.userKey != "") {
db.sql`UPDATE playerdata SET score = ${entity.score} WHERE id = ${entity.player.userKey}`
}
})
屑孤毒顶顶顶,namenb!imgsrc="https://static.cod喵/emoji/codemao/%E7%BC%96%E7%A8%8B%E7%8C%AB_%E7%82%B9%E8%B5%9E.gif"alt="emotion_编程猫_点赞"
点赞0
评论