Node connects to MySql to create database and table

A new project

  1. New project npm init initialization project
  2. Download mysql express package cnpm install mysql express --save
  3. New file app.js
  4. 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.jsyou 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 createdbto see the following
Insert picture description here

Open your Navicat Premium or XAMPP
mine is Navicat
Insert picture description here
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 createdbinto a createpoststablecarriage return
will be able to see the display in the following figure
Insert picture description here
while your terminal will display the following information
Insert picture description here
back to Navicatbe able to see tables create success ...
Insert picture description here
of course, can choose visualization or command-line operation

Published 41 original articles · Likes2 · Visits 1836

Guess you like

Origin blog.csdn.net/weixin_43883485/article/details/104816186
Recommended