的Node.js代碼:無法使用Node.js的來自多個用戶定義的變量來運行MySQL查詢
var express = require("express");
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'myDatabase'
});
var app = express();
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
app.get("/",function(req,res){
var tmdb_id, rel_date, role, title, year, starring, actor, categories,choose,use;
choose = 3;
if (choose == 0 || choose == 1 || choose ==2 || choose==3){
use = categories[choose];
connection.query('
SET @tmdbid:= (SELECT TMDB_ID FROM `MOVIES` WHERE VOTES > 2058 ORDER BY RAND() LIMIT 0,1);
SET @genre:= (SELECT GROUP_CONCAT(GENRE_NAME) FROM `MOVIES_GENRES` WHERE TMDB_ID = @tmdbid);
SET @director:=(SELECT GROUP_CONCAT(DISTINCT NAME) FROM`DIRECTORS` WHERE DID IN (SELECT DID FROM `DIRECTS` WHERE TMDB_ID = @tmdbid));
SET @actors:=(SELECT GROUP_CONCAT(DISTINCT NAME) FROM `ACTORS` WHERE AID IN (SELECT AID FROM `ROLES` WHERE TMDB_ID = @tmdbid));
SET @roles:=(SELECT GROUP_CONCAT(DISTINCT CHAR_NAME) FROM `ROLES` WHERE TMDB_ID = @tmdbid);
SET @plot:= (SELECT OVERVIEW FROM `OVERVIEW` WHERE TMDB_ID = @tmdbid);
SELECT TITLE, RELEASE_DATE, @genre, @director, @actors, @roles, @plot
FROM `MOVIES` WHERE TMDB_ID = @tmdbid', function(err,rows,fields){
console.log(err);
if (!err){
console.log(rows[0]);
}
else
console.log('Error while performing Query.');
});
}
});
app.listen(3000);
查詢:
SET @tmdbid:= (SELECT TMDB_ID FROM `MOVIES` WHERE VOTES > 2058 ORDER BY RAND() LIMIT 0,1);
SET @genre:= (SELECT GROUP_CONCAT(GENRE_NAME) FROM `MOVIES_GENRES` WHERE TMDB_ID = @tmdbid);
SET @director:=(SELECT GROUP_CONCAT(DISTINCT NAME) FROM`DIRECTORS` WHERE DID IN (SELECT DID FROM `DIRECTS` WHERE TMDB_ID = @tmdbid));
SET @actors:=(SELECT GROUP_CONCAT(DISTINCT NAME) FROM `ACTORS` WHERE AID IN (SELECT AID FROM `ROLES` WHERE TMDB_ID = @tmdbid));
SET @roles:=(SELECT GROUP_CONCAT(DISTINCT CHAR_NAME) FROM `ROLES` WHERE TMDB_ID = @tmdbid);
SET @plot:= (SELECT OVERVIEW FROM `OVERVIEW` WHERE TMDB_ID = @tmdbid);
SELECT TITLE, RELEASE_DATE, @genre, @director, @actors, @roles, @plot
FROM `MOVIES` WHERE TMDB_ID = @tmdbid
我試圖挽救定義的所有用戶的變量值和然後在最後顯示它。這段代碼在MYSQL 5.7中使用MYSQL workbench 6.3CE很好。但是當我使用node.js運行此代碼時,我無法獲取輸出,因爲它會引發錯誤。當我下載node_modules時,SQL的版本爲0.9節點。
錯誤:
{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @tmdbid' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0 }
我不知道我要去的地方錯在這裏。
你能告訴我們你的NodeJS代碼嗎? – shennan
我已添加代碼。 – crash
不知道是否有問題,但您在FROM'DIRECTORS' – Gary