Roh*_*mar 6 html javascript mysql node.js
我一直在玩Node.js,我正在用node-mysql编写一些测试应用程序.我正在尝试编写一个自动与数据库建立连接的模块,这样我就不必一次又一次地编写连接代码.这是我写的:
var mysql = require('mysql');
module.exports = function(mysql) {
var client = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345'
});
return client;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将此文件导入我的另一个*.js文件时,我收到一个错误:
~/work : $ node queryInfo.js
/Users/socomo22/work/queryInfo.js:3
client.connect();
^
TypeError: undefined is not a function
at Object.<anonymous> (/Users/socomo22/work/queryInfo.js:3:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Run Code Online (Sandbox Code Playgroud)
因为我是Node.js的新手,所以我不确定我做错了什么.请帮忙!
queryInfo.js //需要上述模块的代码
var client = require('./connectMysql');
client.query("USE node");
client.query("INSERT INTO test(content) VALUES(?)", ['the content'],
function(err, info) {
if(err)
return handle_error(err);
console.log(info.insertId);
});
client.query('UPDATE test SET content = ?', ['new content'], function(err, info) {
if(err)
return handle_error(err);
console.log(info.insertId);
});
client.end();
Run Code Online (Sandbox Code Playgroud)
您可以使用此:
Config.js
var mysql = require('mysql');
var config;
config = {
mysql_pool : mysql.createPool({
host : 'hede',
user : 'hede',
password : 'hede',
database : 'hede'
})
};
module.exports = config;
Run Code Online (Sandbox Code Playgroud)
当您使用此js。您可以这样使用;
var mysqlConf = require('config.js').mysql_pool;
mysqlConf.getConnection(function (err, connection) {
connection.query('{YOUR QUERY}' ,[{FIELDS}], function (err, rows) {
connection.release(); //---> don't forget the connection release.
});
});
Run Code Online (Sandbox Code Playgroud)
在 Node.js 中打开数据库连接通常是异步的。我不知道该模块,但寻找连接到数据库的连接事件或回调。然后你让你的 MySQL 函数接受一个回调函数作为参数。在这里你传递连接。
编辑:
如果连接尚未打开,MySQL 包通过临时排队查询来处理异步连接。然而,打开 MySQL 连接的推荐方法是:
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
Run Code Online (Sandbox Code Playgroud)
一旦执行回调,连接就会真正打开。这是node的核心概念之一。
要使用它,请导入连接模块并具有如下所示的界面:
var db = require("./connectMysql");
db.getConnection(function(err, connection) {
// here u can run queries
});
Run Code Online (Sandbox Code Playgroud)
然后确保 MySQL createClient 仅运行一次,并保存连接以供下次某个模块想要使用它时使用。