简体   繁体   中英

How to create a Nodejs MySQL execute query for values that might not exist

I'm inserting values into a MySQL database using Nodejs mysql2 library.

Here is an example of a prepared statement:

await conn.execute(
    'INSERT INTO Friends (id, user, name, gender) VALUES (UUID(), ?, ?, ?)',
    [ user, body.name, body.gender ]
);

How can I achieve the above if sometimes the body.gender value is not set? I want several attributes in the http request to be optional and insert all allowed values that have been sent in the http request into the database.

The above code gives an error if I leave body.gender out of the http request.

If there is no some data in body or not sending some data from the client to register in the database, you have to put a null value for that row in that column. You can use this JavaScript feature to do this:

await conn.execute(
    'INSERT INTO Friends (id, user, name, gender) VALUES (UUID(), ?, ?, ?)',
    [ user || null, body.name || null, body.gender || null ]
);

Using this possibility, in the absence of any of the data sent in the body, its value is undefined and the value of null is placed in the query.

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