我正在学习使用节点js创建应用程序,正在将节点js连接到mysql,连接成功,但是之后,当我从节点文件中给出“选择”命令时,它会抛出“ ER_NO_DB_ERROR:未选择数据库”错误。 以下是我的文件:
config.js
module.export ={
server : "localhost/phpmyadmin/",
port : "3306",
database : "newdb",
username : "root",
password : ""
}
connection.js
var dbConfig = require("./config")
var sqlInst = require("mysql")
var con = {};
module.exports.createCon = function(callback){
con = sqlInst.createConnection(dbConfig);
con.connect(function(err){
if(err)
{
console.error(err);
// callback(err);
}
else{
console.log("connected");
}
})
module.exports.instSql = function(callback){
let sql = "SELECT * FROM `producdesc`";
con.query(sql,(err,result)=>{
if(err){
console.log(err);
res = err;
}
else {
res = result;
}
});
// return res;
}
}
server.js文件:
const exp = require("express");
var connect = require("./connection")
const app = exp();
app.listen('3000',()=>{
console.log('server strated at port 3000');
})
app.get('/connect',(req,res)=>{
console.log("hello");
connect.createCon();
res.send("connected to database");
})
app.get('/show',(req,res)=>{
let prodRes ;
console.log("in show");
prodRes=connect.instSql();
res.send(prodRes);
})
仅当我尝试“ http://localhost:3000/show”时,数据库中存在数据库和表,错误才会出现。
有人可以让我知道这个问题吗
答案 0 :(得分:0)
在节点mysql
中,属性称为host
和user
,而不是server
和username
。 https://github.com/mysqljs/mysql#connection-options
因此,将您的配置更改为:
module.export = {
host: 'localhost/phpmyadmin/', // This was changed
port: 3306,
database: 'newdb',
user: 'root', // This was changed
password: ''
};