Before know databases are linked mongoodb, that MySql how to link it? Next will be explained in detail.
- Before the link MySql, current computer needs to have an integrated environment, so first install xampp .
- After the installation is complete, start MySql service when it turns green it indicates a successful start.
- Localhost apache provide input into the address in the browser, click on the top right navigation phpmyadmin enter the address of the local database.
- New Folder nodemysql, and initialize the project
npm init
- mysqljs Tutorial
- Install mysql
npm install mysql
- Express install
npm install express
- Installation nodemon
npm install nodemon -g
if installed before you can skip - 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
- 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
But this time there is no data in the database table, then we create a data table
- 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'
});
- 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.
- 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.
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...');
})
})
- 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);
})
})
- 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);
})
})
- 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