Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)(上):https://developer.aliyun.com/article/1420290
Node.js 连接 MySQL
1、安装MySQL数据库
安装 xampp
安装包下载地址: https://sourceforge.net/projects/xampp/files/
进行下载安装
启动
新建数据库,新建表
2、安装 mysql
yarn add mysql 或者 npm install mysql
3、node.js 连接 MySQL
var mysql = require('mysql'); //创建跟数据库的连接 var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '', database : 'test' }); //启动连接 connection.connect(); //执行查询 connection.query('select * from test', function (error, results) { if (error) throw error; console.log(results); });
Node.js nodemon
安装 nodemon
yarn add nodemon 或者 npm install nodemon --save
使用nodemon运行脚本
nodemon 脚本文件
使用package.json脚本
"scripts": { "start":"nodemon index.js" }
使用 npx
npx nodemon index.js
Node.js 操作 MySQL
1、查询
connection.query('select * from test where name=?','test1', function (error, results,fields) { if (error) throw error; console.log(results,'results'); });
2、插入
connection.query('insert into test(name) values (?)','test3', function (error,results, fields) { if (error) throw error; if(results.affectedRows){ console.log('插入成功') } });
3、更新
connection.query('update test set value=? where name=?', [10,'test4'], function (error, results, fields) { if (error) throw error; if (results.affectedRows) { console.log('更新成功') } });
4、删除
connection.query('delete from test where name=?', ['test4'], function (error, results, fields) { if (error) throw error; if (results.affectedRows) { console.log('删除成功') } });
Node.js 应用
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container { width: 600px; margin: 50px auto; } table { width: 100%; text-align: center; } table thead th { background-color: #aaa; } table tbody td { background-color: #eee; padding: 5px } form { margin-bottom: 50px; text-align: center; } input { margin-bottom: 15px; } button { margin-left: 10px } </style> </head> <body> <div class="container"> <!-- 新增数据的表单 --> <form id="form1" action="http://localhost:3030/add" method="post"> 名称:<input type="text" name="name"><br /> 数量:<input type="text" name="value"><br /> <input type="submit" value="提交" /> </form> <!-- 查询数据的输入框 --> <input type="text" placeholder="请输入搜索的名称" id="name"> <button onclick="onGetList()">搜索</button> <!-- 展示数据的列表 --> <table> <thead> <th>名称</th> <th>数量</th> <th>操作</th> </thead> <tbody> </tbody> </table> </div> <script> // 获取数据 var onGetList = function () { // 获取tbody var tbody = document.querySelector('tbody') // 获取搜索框里面的内容 const name = document.querySelector('#name').value // 发送获取数据的请求 fetch('/getlist?name=' + name).then(function (data) { data.json().then(function (result) { tbody.innerHTML = null // 遍历返回的数据,生成每一行数据 result.records.forEach(function (item) { var tr = document.createElement('tr') tr.innerHTML = '<td>' + item.name + '</td>' + '<td>' + item.value + '</td>' var td = document.createElement('td') var button = document.createElement('button') button.innerHTML = '删除' // 点击删除 button.onclick = function () { remove(item) } td.append(button) tr.appendChild(td) tbody.appendChild(tr) }) }) }) } // 删除数据 function remove(item) { // 发送请求,并传递要删除数据的id fetch('/remove', { method: 'POST', body: JSON.stringify({ id: item.id }), headers: { 'Content-Type': 'application/json' } }).then(function (data) { console.log(data) data.json().then(function (result) { console.log('成功') onGetList() }) }) } window.onload = function () { onGetList() } </script> </body> </html>
mysql.js
var mysql = require('mysql'); const sqlConfig = { host: 'localhost', user: 'root', password: '', database: 'test' } let connection = mysql.createConnection(sqlConfig) const sqlFn = function (sql, arr, callback) { connection.query(sql, arr, callback) } module.exports = sqlFn
server.js
const http=require('http') const router=require('./router') http.createServer(function(req,res){ router(req,res) }).listen('3030')
router.js
const sqlFn = require('./index') const url = require('url') const querystring = require('querystring') const fs = require('fs') module.exports = (req, res) => { const { pathname, query } = url.parse(req.url, true) console.log(req.method) if (req.method == 'POST') { let params = '' req.on('data', (chunk) => { params += chunk }) req.on('end', () => { console.log(params) let postParams = querystring.parse(params) if (req.headers['content-type'] == 'application/json') { postParams = JSON.parse(params) } // 处理新增数据的请求 if (pathname == '/add') { sqlFn('insert into test(id,name,value) values (null,?,?) ',[postParams.name, postParams.value], (results) => { if (results.affectedRows) { res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' }) res.end(JSON.stringify({ code: 0, message: '操作成功' })) } }) } //处理删除请求 if (pathname == '/remove') { console.log(postParams) sqlFn('delete from test where id=? ', [postParams.id], (results) => { if (results.affectedRows) { console.log('删除成功') res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' }) res.end(JSON.stringify({ code: 0, message: '操作成功' })) } }) } }) } if (req.method == 'GET') { // 处理获取数据请求 if (pathname == '/getlist') { sqlFn(`select * from test where ${query.name ? 'name=?' : 'name is not null'}`, [query.name], (results) => { console.log(results) res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' }) res.write(JSON.stringify({ code: 0, records: results })) res.end() }) } //处理获取html页面请求 if (pathname == '/index.html') { res.writeHead(200, { "Content-Type": 'text/html;charset=utf8' }) fs.readFile('./index.html', (err, data) => { res.end(data) }) } } }