使用Node.js插入数据

时间:2013-08-13 14:09:00

标签: node.js node-mysql

我正在尝试使用Node.js插入一些数据。我用npm安装了mysql支持。我只是检查了一些源代码,我写了下面的代码,我可以在console.log中跟随sql输出,SQL输出是正确的。但它不会影响mySQL数据库中的任何行。

这是我的代码:

var mysql      = require('mysql');

var connection = mysql.createConnection({
  host     : 'cccc.net',
  user     : 'username',
  password : 'password',
});

var post  = {srcUserID: userSrcID, destUserID: msg.userid, messageContent: msg.txt, messageSendDate:sendDate };

connection.query('INSERT INTO messages VALUES ?', post, function(err, result) {

});

5 个答案:

答案 0 :(得分:16)

它迟到但如果这可以帮助其他人。

 var post  = {id: 1, title: 'Hello MySQL'};
 var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
   // Neat!
 });
 console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'

请注意,他们使用SET而不是VALUES。 INSERT INTO ... SET x = y是一个有效的MySQL查询,而INSET INTO ... VALUES x = y则不是。

答案 1 :(得分:5)

您必须在执行查询之前选择数据库。最简单的方法是将它添加到createConnection调用中的对象:

var connection = mysql.createConnection({
  host     : 'cccc.net',
  user     : 'xxxxx_usr',
  password : 'xxxxxxx',
  database : 'database_name'
});

答案 2 :(得分:4)

正如您在评论中指出的那样,您没有选择数据库:

ER_NO_DB_ERROR: No database selected

因此,您需要先选择一个数据库,然后按预期工作。您需要添加的内容是调用database的{​​{1}}属性,因此您的代码应如下所示:

createConnection

答案 3 :(得分:0)

   const pgp = require('pg-promise')()

// const connection = { host: 'localhost', port: 5432, db: 'users' }
const connection = process.env.NODE_ENV === 'test'
  ? 'postgres:///users_test'
  : 'postgres:///users'
const db = pgp(connection) 

const addUser = (userName, jobName) => {
      return db.one(`
            SELECT j.job_id
            FROM jobs AS s
            WHERE j.job_name = $1`
            , [jobName])
            .then((jobs) => {
        return db.one(`
            INSERT INTO users
            (name, job_id)
            VALUES ($1, $2)
            RETURNING user_id`,
          [userName, jobs.job_id])
    })
    }


     addUser('Micheal', 'teacher')
      .then(console.log)
      .catch(console.error)




      const addUserToCompany = (userName, companyName) => {
        let userId
        let companyId
        return db.one(`
          SELECT user_id
          FROM users
          WHERE name=$1`, [userName])
          .then((user) => {
            userId = user.user_id
            return db.one(`
            SELECT company_id
            FROM companies
            WHERE name=$1`, [companyName])
          })
          .then((company) => {
            ownerId = company.company_id
            return db.one(`
              INSERT INTO companyUsers
                (user_id, company_id)
              VALUES
                ($1, $2)
              RETURNING *`,
              [userId, companyId])
          })
      }
      addUserToCompany('Micheal', 'Code Academy')
        .then(console.log)
        .catch(console.error)



        const updateUserName = (userId, newName) => {
          db.oneOrNone('UPDATE users SET name=$1 WHERE user_id=$2 RETURNING user_id', [newName, userId])
            .then((returnedId) => {
              if (returnedId) return { success: true, message: '' }
              return { success: false, message: `Could not find userId ${userId}` }
            })
            .catch(err => Object({ success: false, message: err.message }))
    }
    updateUserName(17, 'Micheal-Moore')

module.exports = { addUser, addUserToCompany , updateUserName }

答案 4 :(得分:0)

让我在数据库中有 2 个表:(1)brand (2)brand_item。

DROP TABLE IF EXISTS `brand`;
   CREATE TABLE `brand` (
  `brand_id` int(11) NOT NULL AUTO_INCREMENT,
  `brand_key` varchar(255) DEFAULT NULL,
  `brand_name` varchar(2048) DEFAULT NULL,
  `disclaimer` varchar(2048) DEFAULT NULL,
  `description` varchar(2048) DEFAULT NULL,
  `short_description` varchar(2048) DEFAULT NULL,
  `terms` varchar(2048) DEFAULT NULL,
  `created_date` datetime DEFAULT NULL,
  `last_updated_date` datetime DEFAULT NULL,
  `always_show_disclaimer` varchar(2048) DEFAULT NULL,
  `disclaimer_instructions` varchar(2048) DEFAULT NULL,
  `display_instructions` varchar(2048) DEFAULT NULL,
  `terms_and_conditions_instructions` varchar(2048) DEFAULT NULL,
  `image_urls` json DEFAULT NULL,
  `status` varchar(255) DEFAULT NULL,
  `feature` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`brand_id`),
  UNIQUE KEY `brand_key` (`brand_key`)
) ENGINE=InnoDB AUTO_INCREMENT=91 DEFAULT CHARSET=latin1;
 
DROP TABLE IF EXISTS `brand_item`;
CREATE TABLE `brand_item` (
  `brand_id` int(11) DEFAULT NULL,
  `utid` varchar(255) DEFAULT NULL,
  `reward_name` varchar(2048) DEFAULT NULL,
  `currency_code` varchar(2048) DEFAULT NULL,
  `status` varchar(255) DEFAULT NULL,
  `value_type` varchar(255) DEFAULT NULL,
  `reward_type` varchar(255) DEFAULT NULL,
  `is_whole_amount_value_required` varchar(255) DEFAULT NULL,
  `face_value` double(16,2) DEFAULT '0.00',
  `min_value` double(16,2) DEFAULT '0.00',
  `max_value` double(16,2) DEFAULT '0.00',
  `created_date` datetime DEFAULT NULL,
  `last_updated_date` datetime DEFAULT NULL,
  `redemption_instructions` varchar(2048) DEFAULT NULL,
  `countries` varchar(2048) DEFAULT NULL,
  UNIQUE KEY `utid` (`utid`),
  KEY `brand_id` (`brand_id`),
  CONSTRAINT `brand_item_ibfk_1` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`brand_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

插入品牌表的Javascript代码: ON DUPLICATE KEY UPDATE 在 INSERT 查询中得到处理。

async function addToDB(event, brandDetails) {
return new Promise((resolve, reject) => {

let values = `[brandDetails.key,brandDetails.name,brandDetails.disclaimer,brandDetails.description,brandDetails.shortDescription,brandDetails.terms,brandDetails.createdDate,brandDetails.lastUpdateDate,brandDetails.alwaysShowDisclaimer,brandDetails.disclaimerInstructions,brandDetails.displayInstructions,brandDetails.termsAndConditionsInstructions,brandDetails.imageUrls,brandDetails.status]` 

let query = "INSERT INTO ?? (brand_key,brand_name,disclaimer,description,short_description,terms,created_date,last_updated_date,always_show_disclaimer,       disclaimer_instructions,display_instructions,terms_and_conditions_instructions,image_urls,status) VALUES (?) ON DUPLICATE KEY UPDATE brand_key=?, brand_name=?, disclaimer=?, description=?, short_description=?, terms=?, created_date=?,last_updated_date=?, always_show_disclaimer=?, disclaimer_instructions=?,\ display_instructions=?,terms_and_conditions_instructions=?, image_urls=?, status=?";

  MySQLController.executeQuery(event,query, [BRAND_TABLE, values, values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7],values[8],values[9],values[10],values[11],values[12],values[13],values[14]] )
  .then((res)=>{
      console.log("Success in Insertion ", res);
      resolve(res);
  })
  .catch((err)=>{
      console.log("error in DB ",err);
      reject(err);     
  })

  })}

插入brand_item表的Javascript代码: ON DUPLICATE KEY UPDATE 在 INSERT 查询中得到处理。

 async function addToBrandItem(event, fkey, brandItemDetails) {
  return new Promise((resolve, reject) => {
      
       let values = [fkey, brandItemDetails.utid, brandItemDetails.rewardName, brandItemDetails.currencyCode, brandItemDetails.status, brandItemDetails.valueType, brandItemDetails.rewardType,brandItemDetails.isWholeAmountValueRequired, `${brandItemDetails.faceValue}`, `${brandItemDetails.minValue}`, `${brandItemDetails.maxValue}`, brandItemDetails.createdDate,brandItemDetails.lastUpdateDate,brandItemDetails.redemptionInstructions,`${brandItemDetails.countries}`]
      
  let query = "INSERT INTO ?? (brand_id,utid,reward_name,currency_code,status,value_type,reward_type,is_whole_amount_value_required,face_value,min_value,max_value,created_date,last_updated_date,redemption_instructions,countries) VALUES (?)";
  

  AuroraController.executeQuery(event,query , [BRAND_ITEM_TABLE, values, values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7],values[8],values[9],values[10],values[11],values[12],values[13],values[14]] )
  .then((res)=>{
      console.log("Success in Insertion in Bran_item", res);
      resolve(res);
  })
  .catch((err)=>{
      console.log("error in DB ",err);
      reject(err);     
  })

  })}

注意:-为了在 values 数组中保留十进制值,我使用刻度符号来获取它的值 ${}