简体   繁体   English

当我在 ExpressJS 应用中使用 app.post 时,如何获取自动递增的值?

[英]How to get auto-incremented value when I app.post in ExpressJS app?

I have a data form that users enter their first name, last name, and email before users take a test.我有一个数据表单,用户在测试之前输入他们的名字、姓氏和电子邮件。 The data table has a Student_id column that auto-increments every new user.数据表有一个Student_id列,它会自动增加每个新用户。 My issue is trying to figure out how to get that Student_id number after user submits the form, so I can store it in a variable on my Express app, eventually posting that number to another data table to keep track of current user.我的问题是试图弄清楚如何在用户提交表单后获取该Student_id编号,以便我可以将其存储在我的 Express 应用程序上的变量中,最终将该编号发布到另一个数据表以跟踪当前用户。

I've tried the following with no success (most likely doing it wrong):我尝试了以下但没有成功(很可能做错了):

SCOPE_IDENTITY()

LAST_INSERT_ID

app.use(bodyParser.urlencoded({ extended: true }));
app.post('/user-info', (req, res) => {

    var first_name = req.body.first_name;
    var last_name = req.body.last_name;
    var email = req.body.email;

    var sql = `INSERT INTO Govt_profiles (First_Name, Last_Name, Email)
        SELECT ?, ?, ? 
        WHERE NOT EXISTS (SELECT 1 FROM Govt_profiles WHERE Email = ?)`;


    pool.query(sql, [first_name, last_name, email, email], (err, data) => {
        if (err) throw err;
    });
    res.redirect('/questions');

});

I'm able to post my data without issues, I'm just not able to figure out how to get that Student_id number.我可以毫无问题地发布我的数据,只是不知道如何获取该 Student_id 编号。

I've tried the following with no success (most likely doing it wrong): SCOPE_IDENTITY() and LAST_INSERT_ID我尝试了以下但没有成功(很可能做错了): SCOPE_IDENTITY()LAST_INSERT_ID

您必须选择最后一个插入 ID,例如

SELECT LAST_INSERT_ID()

If you're using the node module mysql you should be able to use results.insertId .如果您使用节点模块mysql,您应该能够使用results.insertId

From Getting the id of an inserted row :获取插入行的 id

If you are inserting a row into a table with an auto increment primary key, you can retrieve the insert id like this:如果您将一行插入到带有自动递增主键的表中,您可以像这样检索插入 ID:

connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields) {
  if (error) throw error;
  console.log(results.insertId);
});

In sql you configure the field as auto incremented, no need to insert that filed value.在 sql 中,您将该字段配置为自动递增,无需插入该字段值。 On each insertion it will automatically take incremented value.在每次插入时,它将自动采用递增值。 Normally for primary key we configure AUTO_INCREMENT during table creation.通常对于主键,我们在表创建期间配置 AUTO_INCREMENT。

CREATE TABLE <tablename>(
id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (id));

Then we set a minimum level from which the value should start as this然后我们设置一个最小级别,值应该从这个级别开始

ALTER TABLE <table name> AUTO_INCREMENT=9000;

so you can do the insert query as below所以你可以做如下插入查询

INSERT INTO <tablename>(FirstName,LastName)
VALUES ('Foo','Bar');

I believe that your problem is not with the query.我相信您的问题不在于查询。 It is with how Node.js works.这与 Node.js 的工作方式有关。 It doesn't appear that you are waiting for the information to be returned from the post.您似乎没有在等待帖子返回的信息。 Try running it using a promise or an async/await function.尝试使用 promise 或 async/await 函数运行它。

http://www.acuriousanimal.com/2018/02/15/express-async-middleware.html http://www.acuriousanimal.com/2018/02/15/express-async-middleware.html

app.post('/user-info', async (req, res) => { app.post('/user-info', async (req, res) => {

var first_name = req.body.first_name;
var last_name = req.body.last_name;
var email = req.body.email;

var sql = `INSERT INTO Govt_profiles (First_Name, Last_Name, Email)
    SELECT ?, ?, ? 
    WHERE NOT EXISTS (SELECT 1 FROM Govt_profiles WHERE Email = ?)`;

await pool.query(sql, [first_name, last_name, email, email], (err, data) => {
    if (err) throw err;
});

// await getIdSQL = `SELECT LAST_INSERT_ID()`
// if successful - send result 
// if failure - send error

}); });

On the client side, use the fetch API or AJAX to capture the message and redirect on success.在客户端,使用 fetch API 或 AJAX 来捕获消息并在成功时重定向。

Either the pool is created with the default promise implementation ( require('mariadb'); ) then use池是使用默认承诺实现( require('mariadb'); )创建的,然后使用

try {
   const res = await pool.query(sql, [first_name, last_name, email, email]);
   return res.insertId;
} catch(err) {
    //do something with error;
}

or if pool use callback implementation ( require('mariadb/callback'); ) then use或者如果池使用回调实现( require('mariadb/callback'); )然后使用

pool.query(sql, [first_name, last_name, email, email], (err, data) => {
    if (err) throw err;
    //do something with `data.insertId`
});

Ok I finally figured it out after moving on and returning to this issue.好的,在继续并返回到这个问题之后,我终于想通了。 Thanks for everyone's help, here was my solution in my case.感谢大家的帮助,这是我的解决方案。

app.use(bodyParser.urlencoded({ extended: true }));
app.post('/user-info', (req, res) => {

var first_name = req.body.first_name;
var last_name = req.body.last_name;
var email = req.body.email;

var sql = `INSERT INTO Govt_profiles (First_Name, Last_Name, Email)
    SELECT ?, ?, ? 
    WHERE NOT EXISTS (SELECT 1 FROM Govt_profiles WHERE Email = ?);
    SELECT LAST_INSERT_ID()`;

pool.query(sql, [first_name, last_name, email, email], (err, data) => {
    if (err) throw err;
})
.then(rows => {
    console.log(rows[0].insertId);//<-----here's the freaking last insertId 😆!!!!!!
})
.catch(err => {
    console.log(err);
})

}); });

Another way but not the best.另一种方式,但不是最好的。

By knowing that Student_id is auto_increment value, you can use this sentence:知道Student_id是auto_increment值,可以用这句话:

 SELECT `Student_id` FROM `Govt_profiles` WHERE Student_id=(SELECT MAX(Student_id) FROM `Govt_profiles`);

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

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