我通过输入以下命令提示符命令创建了一个 React 项目
mkdir mysql-test && cd mysql-test
npm init –y
npm install mysql –save
然后我创建了一个名为 app.js 的文件,并放入以下代码:
// app.js
const mysql = require('mysql');
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'rds-mysql-wmcw.cgz0te1dlkah.us-east-1.rds.amazonaws.com',
user: 'masterUsername',
password: 'masterPassword',
database : 'db_wmcw'
});
//try to connect to the mySql database. If an error occurs, display an
error message on the console
con.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
//a connection has been established to the database. Now, run a query against the table 'homepage'
//to retrieve each row and all columns of the table
console.log('Connection established');
con.query('SELECT * FROM homepage', (err,rows) => {
//if an error occurs when reading the data from the table, display the error on the console
if(err) {
console.log(err);
return;
}
//data has been retrieved from the table. display the data to the console
console.log('Data received from Db:\n');
console.log(rows);
});
});
con.end((err) => {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
在我添加 con.query 命令之前,当我在命令提示符下输入 app.js 时,返回的响应是“连接已建立”。所以我知道我正在连接到 mySql 数据库。当我包含 con.query 命令并在命令提示符下输入 app.js 时,出现以下错误:
连接已建立 { 错误:调用退出后无法将查询排入队列。 在 Protocol._validateEnqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:203:16) 在 Protocol._enqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:138:13) 在 Connection.query (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:200:25) 在 Handshake.con.connect (C:\jrs\codercamp\mysql-test\app.js:21:7) 在握手时。 (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:502:10) 在 Handshake._callback (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:468:16) 在 Handshake.Sequence.end (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24) 在 Handshake.Sequence.OkPacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:92:8) 在 Protocol._parsePacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:278:23) 在 Parser.write (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Parser.js:76:12) 代码:'PROTOCOL_ENQUEUE_AFTER_QUIT',致命: false }
在错误的顶部,它指出调用退出后无法将查询排入队列。我不明白为什么系统认为我在调用退出后执行查询。我不会调用 quit ,除非这是我执行 con.end 时发生的情况,但 con.end 是最后执行的语句。这是在查询调用之后。
非常感谢任何帮助。
谢谢。
PS - 我已经包含了主机名、用户 ID、密码和数据库名称,以便于调试。数据库中没有真正重要的数据
最佳答案
好的,所以替代解决方案是卸载 mysql
软件包并使用 mysql2
软件包进行更改。正如作者所说:
MySQL2 is mostly API compatible with mysqljs and supports majority of features
此答案是针对提问者对其帖子的评论
如果你真的想重新分配一行数据,你可以这样做:
const { product_detail, product_description } = results[0];
这是基本语法:D(也许是 ES6)
关于mysql - 使用 mySql 的简单 React 无法读取表记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51451306/