如标题所说,我的SQL代码在phpmyadmin中可以工作,但在从API请求时却不行。 我的API使用mysql包:
npm i mysql
SQL代码:
BEGIN;
INSERT INTO Addresses (address, postal_code, city, state, country)
VALUES('Something', 69420, 'Something', 'Something', 'Something');
SELECT LAST_INSERT_ID() INTO @mysql_address_id;
INSERT INTO Companies (owner, org_nr, name)
VALUES('someid', 133769420, 'Something');
SELECT LAST_INSERT_ID() INTO @mysql_company_id;
INSERT INTO Users (company, member, administrator)
VALUES(@mysql_company_id, 'someid', 1);
INSERT INTO CompanyDetails (shippingAddress, company, shortName, ourReference)
VALUES(@mysql_address_id, @mysql_company_id, 'Something', 'Something');
COMMIT;
在phpmyadmin中这完全正常。
我使用以下方式调用函数:
db.query(
`BEGIN; INSERT INTO Addresses (address, postal_code, city, state, country) VALUES('Something', 69420, 'Something', 'Something', 'Something'); SELECT LAST_INSERT_ID() INTO @mysql_address_id; INSERT INTO Companies (owner, org_nr, name) VALUES('Something', 133769420, 'Something'); SELECT LAST_INSERT_ID() INTO @mysql_company_id; INSERT INTO Users (company, member, administrator) VALUES(@mysql_company_id, 'someid', 1); INSERT INTO CompanyDetails (shippingAddress, company, shortName, ourReference) VALUES(@mysql_address_id, @mysql_company_id, 'Something', 'Something'); COMMIT;`,
(err, result) => {
if (err) return res.status(422).json(err);
return res.status(200).json(result);
}
);
显示的错误是:
{"code":"ER_PARSE_ERROR","errno":1064,"sqlMessage":"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO Addresses (address, postal_code, city, state, country) VALUES('Ve...' at line 1","sqlState":"42000","index":0,"sql":"BEGIN; INSERT INTO Addresses (address, postal_code, city, state, country) VALUES('Something', 69420, 'Something', 'Something', 'Something'); SELECT LAST_INSERT_ID() INTO @mysql_address_id; INSERT INTO Companies (owner, org_nr, name) VALUES('someid', 133769420, 'Something'); SELECT LAST_INSERT_ID() INTO @mysql_company_id; INSERT INTO Users (company, member, administrator) VALUES(@mysql_company_id, 'someid', 1); INSERT INTO CompanyDetails (shippingAddress, company, shortName, ourReference) VALUES(@mysql_address_id, @mysql_company_id, 'Something', 'Something'); COMMIT;"}
有人知道这可能是什么原因引起的吗?任何帮助将不胜感激 :)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我在这里找到了解决方案:https://stackoverflow.com/a/23267627/13214923 原来node-mysql默认不支持多个语句。
通过添加
{multipleStatements: true,}到我的连接池配置中,它就像魔术般地工作了 :)