简体   繁体   English

如何为可能不存在的值创建 Nodejs MySQL 执行查询

[英]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.我正在使用 Nodejs mysql2 库将值插入到 MySQL 数据库中。

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?如果有时未设置body.gender值,我该如何实现上述目标? 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.我希望 http 请求中的几个属性是可选的,并将 http 请求中发送的所有允许值插入数据库。

The above code gives an error if I leave body.gender out of the http request.如果我将body.gender排除在 http 请求之外,上面的代码会出错。

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.如果正文中没有某些数据或未从客户端发送某些数据以在数据库中注册,则必须在该列中为该行输入null值。 You can use this JavaScript feature to do this:您可以使用此 JavaScript 功能来执行此操作:

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.使用这种可能性,在正文中没有发送任何数据的情况下,它的值是undefined的,并且null的值被放置在查询中。

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

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