简体   繁体   English

如何在插入数据之前检查Node.js中的mysql表字段类型

[英]How to check mysql table field type in nodejs before inserting data

i am trying to insert some data into mysql table using nodejs. 我正在尝试使用nodejs将一些数据插入mysql表。 These data are dynamic , so before inserting how can i check the field type , i am facing issue when trying to insert 'date ' to date field type. 这些数据是动态的,因此在插入如何检查字段类型之前,尝试在日期字段类型中插入“ date”时遇到问题。

         for(var i = 0; i < insertdata.length; i++){
                                var post=[];
                                post  = insertdata[i];

                                var querydd = connection.query('INSERT INTO '+ req.body.table_name + ' SET ?', post, function(err, result) {

                                });

                            }

data trying to insert is as follows 尝试插入的数据如下

      { category: 'sd',
          book_id: '56353',
          author_book: 'Sir Alex Ferguson',
           book_title: 'Leading',
          price: '11',
          publication: 'abc',
          publication_date: '12-10-2015' }
     { category: 'df',
       book_id: '73638',
       author_book: 'Eric Smith',
        book_title: 'How Google Works',
        price: '110',
        publication: 'abcdd',
        publication_date: '17-10-2016' }
       { category: 'ffs',
           book_id: '37364',
          author_book: 'William Shakespeare',
           book_title: 'The Merchant of Venice',
           price: '200',
           publication: 'sgre',
           publication_date: '2017-10-2016' }
  1. 12-10-2015 is a string . 12-10-2015string Try convert it to Date by new Date(yyyy-mm-dd) before insert. 尝试在插入之前通过new Date(yyyy-mm-dd)将其转换为Date
  2. Typically for (var i = 0; i < insertdata.length; i++) is a not correct code to insert multiply rows. 通常for (var i = 0; i < insertdata.length; i++)是不正确的代码来插入乘法行。 You don't control execute flow, eg what do if some query fail? 您无法控制执行流程,例如,如果某些查询失败,该怎么办? Read async or promises . 阅读asyncpromises
  3. ('INSERT INTO '+ req.body.table_name + ' SET ?', post is a dangerous code (see SQL-injection). You must be careful with input data. The better way is use placeholder like a insert into mytable set field = ?, field2 = ?, data, ... ('INSERT INTO '+ req.body.table_name + ' SET ?', post是危险代码(请参阅SQL注入)。您必须小心输入数据。更好的方法是使用占位符,例如insert into mytable set field = ?, field2 = ?, data, ...
  4. You can read db-field property from metadata tables . 您可以从元数据表中读取db-field属性。

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

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