mysql 尝试将Node.js连接到托管在Azure上的MariaDB数据库时出现“从池中检索连接超时”错误

67up9zun  于 4个月前  发布在  Mysql
关注(0)|答案(1)|浏览(68)

问题陈述

正如标题所示,我试图连接到托管在Azure上的MariaDB数据库,但我无法确定此错误消息的根本原因。

% node dbTest.js                                        
Total connections:  0
Active connections:  0
Idle connections:  0
SqlError: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10003ms
    (pool connections: active=0 idle=0 limit=5)
    at module.exports.createError (/Users/myuser/nextjs-test/node_modules/mariadb/lib/misc/errors.js:64:10)
    at Pool._requestTimeoutHandler (/Users/myuser/nextjs-test/node_modules/mariadb/lib/pool.js:349:26)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  sqlMessage: 'retrieve connection from pool timeout after 10003ms\n' +
    '    (pool connections: active=0 idle=0 limit=5)',
  sql: null,
  fatal: false,
  errno: 45028,
  sqlState: 'HY000',
  code: 'ER_GET_CONNECTION_TIMEOUT'
}

字符串

最小可复制示例

这是从MariaDB文档中提取的。我只更改了初始化池中的凭据,并将SQL查询从大多数DB模式中无效的内容更改为有效的内容。

// Required Modules
const mariadb = require("mariadb");

//Initialize Pool
const pool = mariadb.createPool({
   host: "<host name or IPv4 address>",
   user: "<user name>",
   password: "<password>",
   database: "<database name>",
   connectionLimit: 100,
});

console.log("Total connections: ", pool.totalConnections());
console.log("Active connections: ", pool.activeConnections());
console.log("Idle connections: ", pool.idleConnections());

async function main() {
   let conn;

   try {
      conn = await fetchConn();

      // Use Connection
      var rows = await get_select(conn);
      for (i = 0, len = rows.length; i < len; i++) {
         console.log("Total connections: ", pool.totalConnections());
         console.log("Active connections: ", pool.activeConnections());
         console.log("Idle connections: ", pool.idleConnections());

         console.log(rows);
      }
   } catch (err) {
      // Manage Errors
      console.log(err);
   } finally {
      // Close Connection
      if (conn) conn.end();
   }
}

// Fetch Connection
async function fetchConn() {
   let conn = await pool.getConnection();
   console.log("Total connections: ", pool.totalConnections());
   console.log("Active connections: ", pool.activeConnections());
   console.log("Idle connections: ", pool.idleConnections());
   return conn;
}

//Get select query
async function get_select(conn) {
   return await conn.query("SELECT 1 AS val");
}
main();


也许不是根本原因
我不认为这是一个网络或防火墙问题,因为我已经将我的IP地址列入白名单,并且我能够使用Python中的mysql.connector以及SQL Developer和MySQL等IDE从同一台机器连接到目标数据库。
我不认为这是数据库配置问题,因为我已经检查了数据库超时设置。如果出现错误消息所示的超时,则可能是来自我的本地机器,而不是数据库。
我不认为这是IPv4与IPv6的问题,因为我已经尝试用IPv4 IP地址替换主机名。此外,StackOverflow上的许多建议解决方案都是针对localhost被用作主机的特定情况,这不是我的用例。
我已确认数据库凭据中没有拼写错误。出于故障排除的目的,我明确包含了数据库凭据,以确保该问题与获取环境变量的问题无关。
我已经确认数据库使用默认端口3306。

附加信息

StackOverflow上的其他OP也遇到了同样的错误,但他们帖子上的答案并没有解决我的问题:linklinklinklinklinklink
上面的大多数StackOverflow链接都有我复制的MRE,但即使在应用了这些帖子中公认的答案后,我在许多情况下也会得到同样的错误(我认为所有情况下,但我已经失去了跟踪)。

系统及包详情

macOS索诺马14.1
节点v20.10.0
email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)

7gs2gvoe

7gs2gvoe1#

  • 我按照MSDOC的参考代码,得到了同样的错误。
  • 对于使用@azure/arm-mariadb的Azure身份,我遵循此DOC

注意事项:
Azure Database for MariaDB is正在停用。我们强烈建议您迁移到Azure Database for MySQL。有关迁移到Azure Database for MySQL的详细信息,请参阅Azure Database for MariaDB发生了什么?

  • 在Azure中,我们在var conn = mysql.createConnection中使用connection string
  • 该代码适用于本地MySQL,对于Azure,连接字符串的格式有所不同。
    本地mysql中:
const mariadb = require('mariadb');

const pool = mariadb.createPool({
  host: '127.0.0.1',
  user: 'root',
  password: 'Password',
  connectionLimit: 5,
  database: 'databaseName', // Add this line to specify the database
});

async function selectAndInsert() {
  let conn;
  try {
    conn = await pool.getConnection();

    // SELECT query
    const selectResult = await conn.query('SELECT * FROM example_table');
    console.log('SELECT Result:', selectResult);

    // INSERT query
    const insertResult = await conn.query('INSERT INTO example_table (name, age) VALUES (?, ?)', ['New Person', 28]);
    console.log('INSERT Result:', insertResult);
  } catch (err) {
    throw err;
  } finally {
    if (conn) return conn.end();
  }
}

// Call the function
selectAndInsert();

字符串


的数据


使用MySQL包编码以连接到Azure Database for MariaDB服务器:

下面的代码连接到数据库,在example_table上执行SELECT查询。

const fs = require('fs');
const mysql = require('mysql');

// Replace these values with your actual database credentials
const dbConfig = {
  host: "Server name",
  user: "Server admin login name",
  password: "your_actual_password",
  database: "your_actual_database",
  port: 3306,
  ssl: { required: true }
};

// Create a connection to the database
const conn = mysql.createConnection(dbConfig);

// Connect to the database
conn.connect((err) => {
  if (err) {
    console.error('Error connecting to database:', err.message);
    return;
  }
  console.log('Connected to the database');
  
  // Perform a SELECT query
  conn.query('SELECT * FROM example_table', (queryErr, results) => {
    if (queryErr) {
      console.error('Error executing SELECT query:', queryErr.message);
      return;
    }
    
    // Process the query results
    console.log('Query results:', results);

    // Close the database connection
    conn.end((endErr) => {
      if (endErr) {
        console.error('Error closing database connection:', endErr.message);
      } else {
        console.log('Database connection closed');
      }
    });
  });
});

本地:

Azure:

相关问题