A new project
- New project npm init initialization project
- Download mysql express package cnpm install mysql express --save
- New file app.js
- Introduce express mysql
const express = require('express')
const mysql = require('mysql')
const app = express()
// 监听3000端口
app.listen("3000",() => {
console.log('server started on port 3000')
})
ps: If you do not have to restart the project each modification can be installed nodemon
global install add sudo under mac sudo cnpm install nodemon -g
then nodemon app.js
you can
Two create a connection
//创建连接
const db = mysql.createConnection({
host:'localhost',
user:'root',
password:'xxxxxx', //密码
// database:'nodemysql' // 这里等数据库创建之后放开就可以
})
//connect 连接数据库
db.connect(err => {
if(err) throw err;
console.log('mysql connected ......')
})
Three create a database
//创建数据库
app.get('/createdb',(req,res) => {
let sql = 'CREATE DATABASE nodemysql'
db.query(sql,(err,result) => {
if(err) throw err
console.log(result)
res.send('Database created ...')
})
})
Access to port 3000 in a browser createdb
to see the following
Open your Navicat Premium or XAMPP
mine is Navicat
create a connection in app.js and let go of the database name
Four create a table
//创建表
app.get("/createpoststable",(req,res) => { // 访问该地址 createpoststable 会返回send内容
let sql = "CREATE TABLE posts(id int AUTO_INCREMENT,title VARCHAR(255),body VARCHAR(255),PRIMARY KEY(id))"
db.query(sql,(err,result) => {
if(err) throw err;
console.log(result);
res.send('posts表已经建立')
})
})
Open the address bar createdb
into a createpoststable
carriage return
will be able to see the display in the following figure
while your terminal will display the following information
back to Navicat
be able to see tables create success ...
of course, can choose visualization or command-line operation