插入两个表不起作用有合适的方法吗?

v8wbuo2f  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(314)

在尝试使此代码正常工作时遇到问题。也许我走错了方向,但实际上我在一个表中插入了一些数据,比如密码用户名和类型,而另一个表将包含客户信息。

connection.connect(function(error) {
  if (error) {
    console.error('error connecting: ' + error.stack);
    return;
  }
  console.log('connected as id ' + connection.threadId);
});

ex.get("/create-user", function(req, res, next)  {
//use err or error?
connection.beginTransaction(function(error){
  if (error) {throw error;}
  connection.query('Insert into users( user_name, user_password, user_type) values (?,?,?)', [req.query.userName, req.query.password, req.query.Customer=1], function (error, results, fields) {
    console.log(req.query);
    if (error) {
      connection.rollback(function(){
        throw error;
      });      
    }

      connection.query('Insert into customers(cust_first_name, cust_last_name, cust_email, cust_city, cust_address, cust_zip_code, cust_state, cust_phone_num, cust_role, cust_website, cust_business_name) values (?,?,?)', [req.query.custFirstName, req.query.custLastName, req.query.custEmail, req.query.custCity, req.query.custAddress, req.query.custZipcode, req.query.custState, req.query.custPhone, req.query.custRole, req.query.custWebsite], [req.query.userName, req.query.password, req.query.Customer=1], function (error, results, fields) {
      if (error) {
        connection.rollback(function(){
          throw error;
        });
      }
      connection.commit(function(error){
          if (error) {
            connection.rollback(function(){
              throw error;
            });
          }
          console.log('transaction complete');
          connection.end();
        });
      });
    res.end(JSON.stringify(results));
    });
  });
});
var server = http.createServer(ex);
server.listen(8080);
t2a7ltrp

t2a7ltrp1#

connection.query('Insert into customers(cust_first_name, cust_last_name, cust_email, 
  cust_city, cust_address, cust_zip_code, cust_state, cust_phone_num, cust_role, 
  cust_website, cust_business_name) 
values (?,?,?)', 
[req.query.custFirstName, req.query.custLastName, req.query.custEmail, 
 req.query.custCity, req.query.custAddress, req.query.custZipcode,  
 req.query.custState, req.query.custPhone, req.query.custRole, 
 req.query.custWebsite], 
[req.query.userName, req.query.password, req.query.Customer=1],

这指定了11列,但只有3列 ? 占位符。
然后在下一个参数中传递10个值。你需要11个。
你莫名其妙地传递了一组额外的三个值,看起来像是先前插入的复制粘贴。
你只需要一个 ? 对于插入中的每一列,然后为每一列传递一个值 ? .
您可能会发现insert的这种替代语法更直观:

Insert into customers set cust_first_name=?, cust_last_name=?, cust_email=?,
   cust_city=?, cust_address=?, cust_zip_code=?, cust_state=?, cust_phone_num=?, 
   cust_role=?, cust_website=?, cust_business_name=?

这是一种mysql自定义语法(在其他品牌的sql中不起作用),但它使匹配 ? 列数的占位符。

相关问题