简体   繁体   中英

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:

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 (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. However, in this case, an exception seems useful to notify the user that username already exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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