Node connection MySql combat fast (CRUD)

Before know databases are linked mongoodb, that MySql how to link it? Next will be explained in detail.

  1. Before the link MySql, current computer needs to have an integrated environment, so first install xampp .
  2. After the installation is complete, start MySql service when it turns green it indicates a successful start.
  3. Localhost apache provide input into the address in the browser, click on the top right navigation phpmyadmin enter the address of the local database.
  4. New Folder nodemysql, and initialize the projectnpm init
  5. mysqljs Tutorial
  6. Install mysql npm install mysql
  7. Express install npm install express
  8. Installation nodemon npm install nodemon -gif installed before you can skip
  9. Create link
const express = require('express');
const mysql = require('mysql');

const app = express();

//创建链接
const db = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    // database : 'my_db'
});

app.listen('3000',() => {
    console.log('服务启动3000');
});

Note:
Create a link field corresponding to the parameter in step 3 to open the page corresponding to the field

6112389-43f3da8f8872a09c.png
QQ screenshot 20190529142002.png

  1. Create a database
//创建数据库
app.get('/createddb',(req,res) => {
    let sql = 'CREATE DATABASE nodemysql';//'CREATE DATABASE'为sql语句,'nodemysql'为数据库名称
    db.query(sql,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.send('database created...');
    })
})

After successfully saved, visit http: // localhost: 3000 / createddb has successfully created a database, then refresh the page phpmyadmin, see the list of databases can be successfully created

6112389-d8de96bbc3ab0438.png
QQ screenshot 20190529143459.png

But this time there is no data in the database table, then we create a data table

  1. Database configuration before the first change, open the database configuration, and set just the new database name
//创建连接
const db = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'nodemysql'
});
  1. Create a table
//创建表
app.get('/createpoststable',(req,res) => {
    let sql = 'CREATE TABLE posts(id int AUTO_INCREMENT,title VARCHAR(255),body  VARCHAR(255),PRIMARY KEY(id))';
    //'CREATE TABLE'创建表,‘posts’为表名称 id为字段,int确定该字段为整型,AUTO_INCREMENT确定该字段自增
    //不同字段间用,隔开
    //VARCHAR(255) 为字符数据,且长度为255
    //'PRIMARY KEY'为主键,一张表中必须有且仅有一个字段为主键

    db.query(sql,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.send('posts created...');
    })

})

Visit http: // localhost: 3000 / createpoststable , the data sheet on the new success.

6112389-dcdef59daf0bf74b.png
New Table

  1. New data
//新增数据
app.get('/addpost1',(req,res) => {
    let data = {
        title:'neo',
        body:'sssss'
    }
    let sql = 'INSERT INTO posts SET ?';
    //'INSERT INTO'新增数据,‘posts’为表名称 ?为自定义插入内容,此处定义的内容为data

    db.query(sql,data,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.send('数据添加成功!');
    })
})

Note garbled phenomenon if the new data will appear as Chinese.

6112389-536e452490fc51f8.png
Garbled

So we need to modify the database configuration items

//创建数据库
app.get('/createddb',(req,res) => {
    let sql = 'CREATE DATABASE IF NOT EXISTS nodemysql default character set utf8 COLLATE utf8_general_ci;';//'CREATE DATABASE'为sql语句,'nodemysql'为数据库名称
    db.query(sql,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.send('database created...');
    })
})
  1. Query data
//查询数据(多条)
app.get('/getposts',(req,res) => {
    let sql = 'SELECT * FROM posts';
    db.query(sql,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.json(result);
    })
})

//查询数据(单条)
app.get('/getposts/:id',(req,res) => {
    let sql =  `SELECT * FROM posts WHERE id = ${req.params.id}`;
    db.query(sql,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.json(result);
    })
})
  1. update data
//更新内容
app.get('/updatepost/:id',(req,res) => {
    let newTitle = '最新标题';
    let sql =  `UPDATE posts SET title = '${newTitle}' WHERE id = ${req.params.id}`;
    db.query(sql,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.json(result);
    })
})
  1. Remove content
app.get('/deletepost/:id',(req,res) => {
    let sql =  `DELETE FROM posts WHERE id = ${req.params.id}`;
    //如果不给条件,会把整个表的数据全部删除
    db.query(sql,(err,result) => {
        if(err) throw err;
        console.log(result);
        res.send('删除成功!');
    })
})

Reproduced in: https: //www.jianshu.com/p/aee57bea3880

Guess you like

Origin blog.csdn.net/weixin_33817333/article/details/91271772