gpt4 book ai didi

mysql - Node JS 中的错误 : ER_INVALID_JSON_TEXT: Invalid JSON text: "Invalid value." at position 1 in value for column '._data' .

转载 作者:行者123 更新时间:2023-12-04 13:15:01 27 4
gpt4 key购买 nike

我想使用 Node js 使用存储过程将 JOSN 数据/对象插入到 mysql 中。首先,我知道那里有一些类似的问题,但我试过了,但仍然没有得到结果。

这是我第一次使用存储过程和 Node js,所以我有表名test_data

测试数据

CREATE TABLE `test_data` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NULL DEFAULT NULL,
`address` VARCHAR(255) NULL DEFAULT NULL,
`city` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2
;

这是存储过程insert_data:

insert_data

CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_data`(
IN `_data` JSON

)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
declare p_name varchar(255) default null;
declare p_address varchar(255) default null;
declare p_city varchar(255) default null;

set p_name= json_unquote(json_extract(_data, '$.name'));
set p_address= json_unquote(json_extract(_data, '$.address'));
set p_city= json_unquote(json_extract(_data, '$.city'));

insert into test_data(name, address, city) values(p_name, p_address, p_city);
END

这是我的 node js 代码:

const con = require('./db/connection');

const _data = {
"name": "Ironman",
"address": "ani@gamil.com",
"city": "bhilai"
}
const sql = "CALL insert_data('"+_data +"')"
con.query(sql, _data,(error, result) => {

if(error){
return console.log("There is error in the query: " + error)
}
console.log(result)
})

错误

There is error in the query: Error: ER_INVALID_JSON_TEXT: Invalid JSON text: "Invalid value." at position 1 in value for column '._data'.

请帮帮我,我做错了什么?

谢谢

最佳答案

在我看来,您实际上并没有传递 JSON 值?

const _data = {
"name": "Ironman",
"address": "ani@gamil.com",
"city": "bhilai"
};

上面是一个 Javascript 对象,而不是它的 JSON 表示。所以在这里

const sql = "CALL insert_data('"+_data +"')"

sql 的实际值将是 "CALL insert_data('[object Object]')",这实际上是无效的。尝试将 sql 转储到控制台以验证情况是否确实如此。

尝试:

const sql = "CALL insert_data('"+ JSON.stringify(_data) +"')"

关于mysql - Node JS 中的错误 : ER_INVALID_JSON_TEXT: Invalid JSON text: "Invalid value." at position 1 in value for column '._data' .,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61360507/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com