nodejs和mysql交互问题
functionget100(){vartiyibai;varmysql=require('mysql');varconnection=mysql.createConne...
function get100() { var tiyibai; var mysql = require('mysql'); var connection = mysql.createConnection({ host: '127.0.0.1', user: 'root', password: '12345678', port: '3306', database: 'dt55' }); connection.connect(); var userGetSql = 'SELECT*FROM 基础题库'; connection.query(userGetSql, function(err, result) { if(err) { console.log('[SELECT ERROR] - ', err.message); return; }; console.log('---------------SELECT----------------'); result = JSON.stringify(result); //result = JSON.parse(result); console.log(result); console.log('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'); tiyibai = result; //return result; }); connection.end( ); console.log(tiyibai); return tiyibai;};console.log(get100());以上是代码图片是执行结果,result得到了结果,但是我这个tiyibai怎么是undefined呢?求解
展开
1个回答
展开全部
1、首先需要安装nodejs 的mysql包
npm install mysql
2、编写nodejs与mysql交互的代码
var mysql = require('mysql');
var TEST_DATABASE = 'ceshi';
var TEST_TABLE = 'user';
//创建连接
var client = mysql.createConnection({
user: 'root',
password: '',
});
client.connect();
client.query("use " + TEST_DATABASE);
client.query(
'SELECT * FROM '+TEST_TABLE,
function selectCb(err, results, fields) {
if (err) {
throw err;
}
if(results)
{
for(var i = 0; i < results.length; i++)
{
console.log("%d\t%s\t%s", results[i].id, results[i].name, results[i].age);
}
}
client.end();
}
);
3、运行结果
D:\nodejs\mysql>node mysql.js
1 u1 23
2 u2 24
3 u3 25
npm install mysql
2、编写nodejs与mysql交互的代码
var mysql = require('mysql');
var TEST_DATABASE = 'ceshi';
var TEST_TABLE = 'user';
//创建连接
var client = mysql.createConnection({
user: 'root',
password: '',
});
client.connect();
client.query("use " + TEST_DATABASE);
client.query(
'SELECT * FROM '+TEST_TABLE,
function selectCb(err, results, fields) {
if (err) {
throw err;
}
if(results)
{
for(var i = 0; i < results.length; i++)
{
console.log("%d\t%s\t%s", results[i].id, results[i].name, results[i].age);
}
}
client.end();
}
);
3、运行结果
D:\nodejs\mysql>node mysql.js
1 u1 23
2 u2 24
3 u3 25
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |