我有两个数组如下
var fieldarray = [ 'category',
'bookid',
'bookauthor',
'booktitle',
'price',
'publication',
'publication_date' ]
var dataarray = [ 'fantasy',
'',
'JKR',
'',
'',
'',
'' ]
fieldarray和dataarray中元素的每次计数都会相同,但元素会不同,在数据数组中,某些元素可以为空,
我必须在mysql语句中使用这些数组
select category,bookid,bookauthor,booktitle,price,publication,publication_date from tbl_books where category like '%fantasy%' OR bookauthor like '%JKR%'
如何在nodejs中基于fiedarray和dataarray元素动态生成mysql语句
2条答案
按热度按时间gcuhipw91#
使用reduce准备一个带有数据的map-first链接字段
现在使用
join
以及map
```var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like '%" + map[f] + "%'")).join(" AND ");
var fieldarray = ['category',
'bookid',
'bookauthor',
'booktitle',
'price',
'publication',
'publication_date'
]
var dataarray = ['fantasy',
'',
'JKR',
'',
'',
'',
''
];
var map = fieldarray.reduce((a, c, i) => (dataarray[i] && (a[c] = dataarray[i]), a), {});
var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like '%" + map[f] + "%'")).join(" AND ");
console.log(query);
var query = "SELECT " + fieldarray.join(" , ") + "from tbl_books where " + Object.keys(map).map(f => (f + " like ?")).join(" AND ");
connection.query( query, Object.values(map), function (error, results, fields) {
if (error) throw error;
// ...
});
ncgqoxb02#
只需遍历dataarray,检查字段是否为空,并将其连接到结果查询。始终确保舒尔不会受到sql注入的影响!