ដើម្បីបង្កើតតារាងទិន្នន័យនៅក្នុងមូលដ្ឋានទិន្នន័យ MySQL យើងចាំបាច់ត្រូវប្រើប្រាស់បញ្ជា «CREATE TABLE» នៃភាសា SQL ។ ពិនិត្យកម្មវិធីខាងក្រោមនេះ៖
import express from 'express'
import path from 'path'
const app = express()
const port = process.env.PORT || 3000
const __dirname = path.resolve()
import index from './routes/index.js'
import backend from './routes/backend.js'
import con from './models/connectMySQL.js'
app.use('/',function(req,res,next){
req.con = con
req.__dirname = __dirname
next()
})
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.urlencoded({extended:false}))
app.use(express.json())
app.use('/',index)
app.use('/backend',backend)
app.listen(port,function(){
console.log(`This application is listening to the port: ${port}`)
})
//models/connectMySQL.js
//npm install mysql
import mysql from 'mysql'
let con = mysql.createConnection({
host: "localhost",
user: "root",
password: "mysql",
database: "mydb"
})
con.connect(function(err){
if (err) throw err
console.log("Connected to the main MySQL!!")
})
export default con
/* ./routes/index.js */
import express from 'express'
import createTable from '../models/mysql.js'
const index = express.Router()
index.use(createTable)
index.get('/',(req,res)=>{
res.render('base',req.data)
})
export default index
//models/mysql.js
function createTable(req,res,next){
let sql = `CREATE TABLE IF NOT EXISTS users(
userid INT AUTO_INCREMENT PRIMARY KEY,
username TEXT,
gender TEXT
)`
req.con.query(sql,function(err){
if(err) throw err
req.data = {}
req.data.message = `Users table was created`
next()
})
}
export default createTable