const mysql = require("mysql2/promise");
const pool = mysql.createPool({
host: "host.mysql.database.azure.com",
user: "user",
password: "password",
database: "db",
port: 3306,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
async function init() {
// Initialize the connection
try {
const connection = await pool.getConnection();
console.log("Connected to the MySQL server.");
connection.release();
} catch (error) {
console.error(`Error connecting to the MySQL server : ${error.message}`);
}
}
init();
当我在 win11 中运行此代码时“连接到 MySQL 服务器”。但在 wsl2 (ubuntu) 中“连接到 MySQL 服务器时出错”为什么会发生这种情况?我该如何解决这个问题
Azure上托管的mysql服务器在wsl2(ubuntu)中无法访问,但在win11中可以访问
但是当我尝试在 wsl2 中连接“mysql --host=host.mysql.database.azure.com --user=user --password=password”时,它的工作
连接 MySQL 服务器时出错
此错误是由于代码中未提供
.pem
文件路径而导致的。通过提供该文件路径解决了相同的错误,您可以在 Azure networking
中的 settings
下下载该文件 mysqlserver
,如下所示。
将文件移至项目文件路径并在代码中提供该路径。以下是成功连接到 Azure MySQL 并从 MySQL 数据库检索数据的示例代码。
const fs = require('fs');
const mysql = require('mysql2/promise');
async function main() {
try {
// Create a MySQL connection using the provided connection string
const conn = await mysql.createConnection({
host: "*******",
user: "user91",
password: "*****",
database: "db",
port: 3306,
ssl: {
ca: fs.readFileSync("C:/Users/*****.crt.pem")
}
});
console.log("Connected to the MySQL server.");
const [rows, fields] = await conn.execute('SELECT * FROM Table1');
console.log(rows);
conn.end();
} catch (error) {
console.error(`Error connecting to the MySQL server: ${error.message}`);
}
}
main();
输出: