在Node.js中,可以使用回调函数或Promise来处理等待MySQL连接结束的情况。
使用回调函数的方法如下:
npm install mysql
const mysql = require('mysql');
const pool = mysql.createPool({ ... });
pool.getConnection((err, connection) => { ... });
connection.query('SELECT * FROM table', (err, results) => { ... });
connection.release();
完整的示例代码如下:
const mysql = require('mysql');
const pool = mysql.createPool({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
pool.getConnection((err, connection) => {
if (err) {
console.error('Error connecting to MySQL:', err);
return;
}
connection.query('SELECT * FROM table', (err, results) => {
if (err) {
console.error('Error executing query:', err);
return;
}
console.log('Query results:', results);
connection.release();
});
});
使用Promise的方法如下:
npm install mysql2
const mysql = require('mysql2/promise');
const pool = mysql.createPool({ ... });
const connection = await pool.getConnection();
const [rows, fields] = await connection.execute('SELECT * FROM table');
connection.release();
完整的示例代码如下:
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
(async () => {
try {
const connection = await pool.getConnection();
const [rows, fields] = await connection.execute('SELECT * FROM table');
console.log('Query results:', rows);
connection.release();
} catch (err) {
console.error('Error executing query:', err);
}
})();
以上是使用Node.js进行MySQL连接的基本方法。在实际应用中,可以根据具体需求进行适当的调整和优化。如果需要更多关于MySQL连接的详细信息,可以参考腾讯云的MySQL产品文档:MySQL产品文档
领取专属 10元无门槛券
手把手带您无忧上云