简体   繁体   English

如果 postgresql POOL 查询不存在,如何插入用户名

[英]How to insert a username if it doesn't already exist with a postgresql POOL query

I am making a game and I recently added a server database score saver but I can't figure out how to insert a username only if it doesn't already exist here is the following query:我正在制作一个游戏,我最近添加了一个服务器数据库分数保护程序,但我无法弄清楚如何插入一个用户名,如果它不存在这里是以下查询:

const addUser = (req, res) => {
    const {username, score} = req.body;
    pool.query(
        'INSERT INTO userlist (username, score) VALUES ($1, $2)',
        [username, score],
        (err) => {
            if(err){
                throw err;
            }
            res.status(201).json({status: "success", message: "User added."});
        },
    );
}

I am guessing I'll have to change the query also here is my SQL code for creating the table:我猜我必须更改查询也是我的SQL代码用于创建表:

CREATE TABLE userlist(
    ID SERIAL PRIMARY KEY,
    username VARCHAR(255),
    score VARCHAR(255)
);

use an if statement to identify if the username exist and then update it使用 if 语句来识别用户名是否存在,然后更新它

 if (Users::where('name', $request->user_name)->exists()) { return response()->json(['record exist']); } else { $save = new Users; $save->name = $request->user_name; $save->save(); return response()->json(['User saved successfully.']); }

The best way to handle this is to let the database validate the uniqueness of the username:处理这个问题的最好方法是让数据库验证用户名的唯一性:

alter table userlist add constraint unq_userlist_usename unique(username);

Now if you attempt to insert a single row, then it will return an error if the row already exists.现在,如果您尝试插入单行,那么如果该行已经存在,它将返回错误。

If you don't want an error you can use an on conflict clause.如果您不希望出现错误,可以使用on conflict子句。 However, in this case, an exception seems useful to notify the user that username already exists.但是,在这种情况下,通知用户用户username已经存在的异常似乎很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM