Write the Code. Change the World.

8月 29

node.js的mysql模块比较多,有mysql,mysqli,还有mariasql以及node-mariadb。针对服务器的环境,使用对应的模块。因此,踩过不少坑。

环境差异

服务器装的mysql环境,php7或php7以下

安装对应模块:

npm install mysql  // php7以下
npm install mysqli // php7


使用:

const mysql = require('mysql');

// First you need to create a connection to the db
const con = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'lovenode'
});

con.connect((err) => {
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});

con.end((err) => {
  // The connection is terminated gracefully
  // Ensures all previously enqueued queries are still
  // before sending a COM_QUIT packet to the MySQL server.
});

或使用连接池

const mysql = require('mysql');
const pool = mysql.createPool({
        host:'localhost',
        user:'root',
        password:'11111111',
        database:'lovenode'
});

const query = function(dbname, sql , callBack)
{
    pool.getConnection(function(error , conn){
        if(error)
        {
            callBack(error , null , null);
        }
        else
        {
            conn.query(sql , function(qerror , vals , fields){
                conn.release();
                callBack(qerror , vals , fields);
            });
        }
    });
}
module.exports = query;

然后在其他模块调query方法就可以了。

服务器装的mariadb

安装对应模块:

npm install mariasql  
npm install node-mariadb 

使用请参考:
https://npm.runkit.com/mariasql

https://yarnpkg.com/en/package/connect-mariasql

参考

https://www.sitepoint.com/using-node-mysql-javascript-client/

https://www.npmjs.com/package/connect-mariasql

https://www.npmjs.com/package/node-mariadb

https://mariadb.com/kb/en/the-mariadb-library/mariasql-for-nodejs/

发表评论

电子邮件地址不会被公开。 必填项已用*标注