如何从数据库中获取最后插入的ID并将其发送到组件?

时间:2019-05-02 15:48:14

标签: mysql node.js reactjs express jsx

我想从获取API的数据库中获取最后一个ID,

问题出在表MaterialUnit materialID显示0

console.log在服务器上工作正常!

这是server.js

app.get('/AddProducts', function (req, res) {
    const { materialName, description, categoryID, manufactureID, currencyID} = req.query;
    const INSERT_MATERIAL = `INSERT INTO material (materialName, description, categoryID, manufactureID, currencyID) VALUES 
                                ('${materialName}','${description}','${categoryID}','${manufactureID}','${currencyID}')`;
    connection.query(INSERT_MATERIAL, (error, result) => {
        if(error) {
            return res.send(error)
        }
        else {
            console.log(result.insertId);
            return res.json({id: result.insertId})
        }
    });
});

app.get('/AddMaterialUnits', function (req, res) {
    const { materialID, unitID, def, rate, price, vat, bar} = req.query;
    const INSERT_MATERIAL = `INSERT INTO materialunit (materialID, unitID, barcodeNo, salePrice, vatValue, isdefault, rate) VALUES 
                                ('${materialID}','${unitID}','${bar}','${price}','${vat}','${def}' ,'${rate}')`;
    connection.query(INSERT_MATERIAL, (error, result) => {
        if(error) {
            return res.send(error)
        }
        else {
            return res.send(result)
        }
    });
});

,然后在组件中:

 AddProduct() {
        let url1 = `http://localhost:3000/AddProducts?materialName=${this.state.name}&description=${this.state.description}&categoryID=${this.state.catID}&manufactureID=${this.state.manID}&currencyID=${this.state.curID}`;
        fetch(url1)
            .catch(error => console.error(error))
            .then(alert("Added successfully"))
            .then((result) => this.setState({materialID: result.id}))
            .then(alert(this.state.materialID));


        this.state.materialUnits.map(obj =>
            fetch(`http://localhost:3000/AddMaterialUnits?materialID=${this.state.materialID}&unitID=${obj.unit.id}&def=${obj.default.value}&rate=${obj.rate}&price=${obj.price}&vat=${obj.vat}&bar=${obj.barcodeNo}`)
                .catch(error => console.error(error))
                .then(alert("Added successfully"))
            )
    }

1 个答案:

答案 0 :(得分:1)

问题是id未设置为AUTO_INCREMENT,它始终是0。要解决此问题,您需要将其手动添加到您不建议的sql语句中。例如INSERT INTO MATERIAL (id, ...) VALUES(12, ...)

让MySQL为您完成增量。通过在phpmyadmin中运行以下命令,修改表并将id设置为AUTO_INCREMENT

ALTER TABLE `material` ADD INDEX(`id`);
ALTER TABLE `material` MODIFY COLUMN id INT AUTO_INCREMENT

注意:在运行这些查询之前,您需要清空表。

enter image description here

如果遇到错误,则可能需要重新创建表。使用以下命令删除表并创建一个新表。根据自己的喜好更改列的长度/值。

CREATE TABLE `material` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `materialName` varchar(500) NOT NULL,
  `categoryID` varchar(500) NOT NULL,
  `description` varchar(500) NOT NULL,
  `manufactureID` varchar(500) NOT NULL,
  `currencyId` varchar(500) NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;