I am converting the old java code to node.js. First, I refer to this page, I used the prepared statement sample code. However, I found that the sample code quite clumpy, so I give up to use this code.
After that, I found the promise method, the example code is much simpler. So, I created a database class for accessing a MySQL Database.
class DBO
{
constructor(){
const mysql = require('mysql2');
const dbConfig={
charset :"utf8",
host :"yourServer",
user :"userName",
password :"password",
port :3306,
database :"school"
};
dbConfig["multipleStatements"]=true;
dbConfig["insecureAuth"]=true;
const connection = mysql.createConnection(dbConfig);
/************************
* Get a student record *
************************/
this.getStudent=async(stdId=>{
let sqlString ="select * from student where id=?";
return await executeQuery(sqlString,[stdId]);
});
/*******************************
* Get a list of student record *
********************************/
this.getStudentList=async(year, month)=>{
let sqlString ="select * from student";
return await executeQuery(sqlString);
}
this.close=()=>{
connection.end(err=>{
if (err) throw err;
console.log("Disconnect from "+dbConfig["host"]+" successfully!");
});
}
/************************************************************************
* Put the query code into a function for making the code more readable.*
************************************************************************/
function executeQuery(sql,para){
return connection.promise().query(sql,para)
.then(([rows]) => {
return rows
})
.catch(err=>{
throw(err);
})
}
}
}
The following sample code is used to call the object directly.
let dboObj=new DBO();
dboObj.getStudentList()
.then(result=>{
console.log("Get Student List ok");
})
.catch(err=>{
console.log("Some wrong when getting data:"+err);
})
.finally(()=>{
dboObj.close();
});
To call the DBO object from another object:
class Student
{
constructor(stdId){
this.id='';
this.name='';
this.class='';
if (stdId!==undefined){
let DBO=require("./dbo.js");
let dboObj=new DBO();
dboObj.getStudent(stdId)
.then(result=>{
this.id=stdId;
this.name=result.name;
this.class=result.class;
})
.catch(err=>{
console.log("Some wrong when getting a student record:"+err);
})
.finally(()=>{
dboObj.close();
});
}
}
static async getStudentList(){
let DBO=require("./dbo.js");
let dboObj=new DBO();
let resultObj={};
try{
let resultList=await dboObj.getStudentList();
resultList.forEach(result=>{
let studentObj=new Student();
studentObj.name=result.name;
studentObj.class=result.class;
resultObj[result.id]=studentObj;
});
return resultObj;
}
catch(err){
throw(err);
}
finally{
dboObj.close();
}
}
}
#javascript
#mysql