Nodejs connects to the mysql database and describes the basic knowledge points, nodejsmysql

Source: Internet
Author: User

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,__filenameObtain the path of the current file
2,__dirnameGet the directory of the current file
3,process.cwd()Get the directory of the current project

II. Introduction and export of Files

1. UserequireImport File

2. Usemodule.exportsExport the specified variables, methods, and objects in the file.

III,nodeProject 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 separatelyrouterFiledemo

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. UseejsTemplate

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. AboutejsUse 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. UsemysqlDatabase

1.moduleCreatedb.jsFile

'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.routerView 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.queryGet 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. AboutnodeReturnjsonMethod

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.