首先,确保你已经安装了 mysql 和 mysql2 模块。你可以使用以下命令进行安装:
npm install mysql mysql2
然后,可以使用以下代码建立一个连接池并执行一些基本的查询:
// 引入需要的模块
const mysql = require('mysql2');
// 创建连接池
const pool = mysql.createPool({
host: 'your_mysql_host',
user: 'your_mysql_user',
password: 'your_mysql_password',
database: 'your_mysql_database',
waitForConnections: true,
connectionLimit: 10, // 连接池中最大连接数
queueLimit: 0 // 无限制等待队列长度
});
// 从连接池中获取连接并执行查询
pool.getConnection((err, connection) => {
if (err) {
console.error('Error getting MySQL connection: ' + err.message);
return;
}
// 执行查询
connection.query('SELECT * FROM your_table', (queryErr, results, fields) => {
// 释放连接
connection.release();
// 处理查询结果
if (queryErr) {
console.error('Error executing query: ' + queryErr.message);
return;
}
console.log('Query results:', results);
});
});
在上面的示例中,我们使用 mysql2 模块创建了一个 MySQL 连接池,并从连接池中获取连接执行查询。请替换 your_mysql_host、your_mysql_user、your_mysql_password 和 your_mysql_database 为你的 MySQL 数据库的实际信息,以及 your_table 为你要查询的表名。
此外,注意在查询结束后要使用 connection.release() 来释放连接,确保连接池可以重新使用连接。
这只是一个简单的示例,你可以根据实际需求进一步扩展和优化代码。
转载请注明出处:http://www.zyzy.cn/article/detail/8035/MySQL