我的.js文件包含以下代码:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});
function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}
// function go(){select(3,"tablename");} or select(3,"tablename");
从button.onClick()调用function.go()。 当我通过"节点filename.js"从控制台运行它时它工作正常并显示正确的数据,但它不能从button.onClick()工作。
我做错了什么?
答案 0 :(得分:0)
你的代码错了。
你写过
var mysql = require(‘mysql'); var connection = mysql.createConnection({host: ‘localhost';user: 'root',password: 'password',database: ‘databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});
应该是
var mysql = require('mysql'); var connection = mysql.createConnection({host: 'localhost';user: 'root',password: 'password',database: 'databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});
在许多地方,您已使用‘
开始使用'
结尾的字符串,这可能会导致问题。
答案 1 :(得分:0)
您应该使用单引号或双引号来包含字符串。您使用了`而不是'
在主持人之后删除分号:' localhost'。应该有一个逗号而不是分号
你的代码应该是这样的
var connection = mysql.createConnection({host:'localhost',user:'root',password:'password',database: 'databasename'});
function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {
var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */
});
}
答案 2 :(得分:0)
我认为你混合同步和异步。你需要回调查询
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'
});
function select(id, tablename, callback){
connection.connect();
connection.query(`SELECT ${tablename}.property from databasename.${tablename} where id = ?`, [id], callback);
connection.end();
}
function go () {
select(3, "tablename", function (err, result) {
// mysql response
});
}