Nodejs connects to the mysql database and describes the basic knowledge points, nodejsmysql
This article describes how to connect nodejs to the mysql database and its basic knowledge. We will share this with you for your reference. The details are as follows:
I. Several common global variables
1,__filename
Obtain the path of the current file
2,__dirname
Get the directory of the current file
3,process.cwd()
Get the directory of the current project
II. Introduction and export of Files
1. Userequire
Import File
2. Usemodule.exports
Export the specified variables, methods, and objects in the file.
III,node
Project directory structure
Demo
Package. json the package or module on which the current project depends
Router stores the route File
View storage module
Public static files
Module Writing module, such as database
App. js main portal File
4. Write the routing view separatelyrouter
Filedemo
1. view files
Const express = require ("express"); const router = express. router (); router. get ("/", (req, res) => {res. send ("hello word") ;}); router. get ("/article", (req, res) => {res. send ("I am an article List");}) module. exports = router;
2. Call
'use strict';const express = require("express");const app = express();app.use("/",require("./router/03_router"))app.use("/app",require("./router/03_router1"))app.listen(3000);
V. Useejs
Template
1. installation required, but not introduced
npm install ejs --save
2. Configure in the main file
// Configure the file path of the template app. set ("views" ,__ dirname + "/views"); // configure the template engine app. set ("view engine", "ejs ");
3. Use
①. Template File
<! Doctype html>
② Rendering templates in Routing
'Use strict '; const express = require ("express"); const router = express. router (); router. get ("/", (req, res) => {// you can directly use res. render ("03_index"); res. render ("03_index.ejs") ;}); router. get ("/article", (req, res) => {res. send ("I am an article List");}) module. exports = router;
③ Main file
'Use strict '; const express = require ("express"); const app = express (); // configure the Template File Path app. set ("views" ,__ dirname + "/views"); // configure the template engine app. set ("view engine", "ejs"); app. use ("/", require (". /router/03_router ") app. use ("/app", require (". /router/03_router1 ") app. listen (0, 3000 );
Vi. Aboutejs
Use of template files
1. return data
... Let dataset = {name: "Zhang San", age: 20, books: ['Romance of the Three Kingdoms ', 'travel to the west', 'Dream of Red Mansions ', 'Water barri']} res. render ("03_index.ejs", dataset );...
2. Common Fields
3. Iterative Array
<ul> <% for(let i in books){%> <li><%= books[i] %></li> <%}%></ul>
7. Load Static files
1. configuration in the main file
// Set static file loading (js, css, img) app. use (express. static (_ dirname + "/public "));
2. Use in the template
<link rel="stylesheet" href="./css/bootstrap.css" rel="external nofollow" ><script type="text/javascript" src="./js/jquery-3.1.1.min.js"></script>...
8. Usemysql
Database
1.module
Createdb.js
File
'Use strict '; const mysql = require ("mysql "); /*** expose all methods. * @ param SQL statement * @ param arg is passed to the parameters in the SQL statement. You can leave the * @ param callback function empty, do not write */module. exports = function (SQL, arg, callback) {// 1. create a connection (based on your own database configuration) let config = mysql. createConnection ({host: "localhost", // database address user: "root", // database Username password: "root", // Database password port: "3306 ", // mysql database port number database: "mybatistest" // use that database}); // 2. start to connect to the Database config. connect (); // 3. add, delete, modify, and query the database config. query (SQL, arg, (err, data) =>{ callback & callback (err, data) ;}) // 4. disable Database config. end ();}
2.router
View query data
① Introduce files
// Import the database file const db = require ("../module/db ");
② Use in views
router.get("/", (req, res) => { db("select * from m_dept",(err,data)=>{ console.log(data); res.render("03_index.ejs",{data:data}); })});
3. Add data
① For the front-end page, see the code case
② Passreq.query
Get user data Parameters
Router. get ("/regist", (req, res) => {// obtain the input parameter, provided that name console is written on the input. log (req. query); db ("insert into student (name, age) values (?,?) ", [Req. query. username, req. query. age], (err, data) => {console. log (data); if (data) {res. send ("succeeded ");}})})
IX. Aboutnode
Returnjson
Method
In the frontend backend separated development mode, the data returned by the backend is generally json, And the ejs template engine is not required.
... Res. json ({info: "successful", code: 1 });...
10. Code cases in this chapter on githubHttps://github.com/kuangshp/node-pro1
I hope this article will help you design nodejs programs.