【问题标题】:How to convert a connection to a pool connection in MySQL?如何将连接转换为 MySQL 中的池连接?
【发布时间】:2020-12-24 17:39:19
【问题描述】:

我。我编写了下面的代码,但我最近了解了池连接,根据我阅读的内容,它更好。我只是不明白如何将连接导出到不同的文件。所以,如果你能指导我如何做到这一点,我将不胜感激。谢谢。

connection.js:

var mysql = require('mysql');
 
const con = mysql.createConnection({
      host:'127.0.0.1', // host of server
      user:'root', // MySQL user
      password:'BLABLABLA', // MySQL password
      database: "rpg"
    });
    
exports.con = con

数据库.js:

const con = require('./connection').con;

mp.events.add('playerJoin', (player) => {
    con.query('INSERT INTO BLA BLA BLA', function (err, result) {
//ETC ETC

基本上,我想知道如何导出、导入和查询。我正在使用 MySQL Workbench 8.0。非常感谢。

【问题讨论】:

    标签: javascript mysql sql node.js mysql-workbench


    【解决方案1】:

    创建池的代码与您现在的代码非常相似。唯一的区别是从池中请求连接的额外步骤。

    connection.js

    const mysql = require('mysql');
    
    const pool = mysql.createPool({
      connectionLimit: 10,
      host: "localhost",
      user: "user",
      password: "password",
      database: "rpg"
    });
    
    
    exports.pool = pool;
    

    数据库.js

    const pool = require("./connection").pool;
    
    // Ask the pool for a connection
    pool.getConnection((err, conn) => {
        if(err){
        
            // Do something with the error
      
        } else {
      
            // Do something with the connection and release it after you're done
            conn.query('INSERT INTO BLA BLA BLA', (err, rows) => {
                // Do something with the result
    
                // release the connection after you're done so it can be reused
                conn.release();
            });
        }
    
    });
    

    【讨论】:

    • 谢谢。我只有一个疑问。 conn.query 是错误的吗?应该是 pool.query 吗?如果不是,我在哪里定义 conn?谢谢!
    • 不,conn 是连接本身。池只是一组连接,因此您向它请求一个连接,然后使用该连接来执行您的查询。 conn 变量是 pool.getConnection 回调中的一个参数
    • 啊!我错过了。谢谢!
    猜你喜欢
    • 2013-08-20
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 2015-09-26
    • 2018-03-22
    • 1970-01-01
    • 2011-10-07
    • 2013-09-01
    相关资源
    最近更新 更多