如何将 JSON 结构中的多行插入到 MySQL 列
How to insert multiple rows from JSON structure to MySQL column
我需要将多个 json 值插入 mysql 列。
这里我有一个 table 名为 client
query = ' INSERT INTO client (user_id,client_id,tenant_id) values ?'
let queryClient = []
queryClient.push(clientData.user_id)
queryClient.push(clientData.client_id);
queryClient.push(clientData.tenant_id);
之前我把req.body
分配给了clientData
这里是 mysql 数据库的连接
var queryMapClientIn = mysql.format(query, [queryClient])
const newMapClient = await conPool.query(queryMapClientIn, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
这是代码,json数据是:
{
"user_id" : 101,
"client_id": 999,
"tenant_id" : 1,
"additionalClient" : [
{"user_id" : 130},
{"user_id" : 131}
]
}
这是 json 数据,我需要将多个 user_id
推入 sql table 上的 user_id
列。我可以知道如何在此 table.
上插入多个 user_id
您可以创建一个二维数组来插入多行。
let clientData = {
"user_id" : 101,
"client_id": 999,
"tenant_id" : 1,
"additionalClient" : [
{"user_id" : 130},
{"user_id" : 131}
]
};
let queryClient = [[clientData.user_id, clientData.client_id, clientData.tenant_id]];
if (clientData.additionalClient) {
let additionalClients = clientData.additionalClient.map(({user_id}) => [user_id, clientData.client_id, clientData.tenant_id]);
queryClient = queryClient.concat(additionalClients);
}
let query = 'INSERT INTO client (user_id,client_id,tenant_id) values ?';
const newMapClient = await conPool.query(query, queryClient, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
我需要将多个 json 值插入 mysql 列。 这里我有一个 table 名为 client
query = ' INSERT INTO client (user_id,client_id,tenant_id) values ?'
let queryClient = []
queryClient.push(clientData.user_id)
queryClient.push(clientData.client_id);
queryClient.push(clientData.tenant_id);
之前我把req.body
分配给了clientData
这里是 mysql 数据库的连接
var queryMapClientIn = mysql.format(query, [queryClient])
const newMapClient = await conPool.query(queryMapClientIn, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
这是代码,json数据是:
{
"user_id" : 101,
"client_id": 999,
"tenant_id" : 1,
"additionalClient" : [
{"user_id" : 130},
{"user_id" : 131}
]
}
这是 json 数据,我需要将多个 user_id
推入 sql table 上的 user_id
列。我可以知道如何在此 table.
user_id
您可以创建一个二维数组来插入多行。
let clientData = {
"user_id" : 101,
"client_id": 999,
"tenant_id" : 1,
"additionalClient" : [
{"user_id" : 130},
{"user_id" : 131}
]
};
let queryClient = [[clientData.user_id, clientData.client_id, clientData.tenant_id]];
if (clientData.additionalClient) {
let additionalClients = clientData.additionalClient.map(({user_id}) => [user_id, clientData.client_id, clientData.tenant_id]);
queryClient = queryClient.concat(additionalClients);
}
let query = 'INSERT INTO client (user_id,client_id,tenant_id) values ?';
const newMapClient = await conPool.query(query, queryClient, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});