nodejs笔记之连接mysql数据库

时间:2021-12-22 19:41:43

1.安装mysql模块;

npm install mysql

2.引入mysql模块

创建一个server.js文件

const http = require("http");
const mystatic = require("./mystatic")
const mysql = require("mysql"); http.createServer((req,res)=>{
console.log(req.url);
mystatic(req,res) // 连接数据库
const connection = mysql.createConnection({
host:"localhost",
user:"root",
password:"root",
database:"yuedu_db",
charset:"UTF8_GENERAL_CI"
})
connection.connect(); if(req.url =="/api/getGoods"){
connection.query("select * from t_types",function(error,results,fields){
if(error) throw error;
res.writeHead(200,{"Content-Type":"text/plain;charset=utf-8;"});
res.end(JSON.stringify(results))
}) }else if(req.url == "/api/getUsers"){
connection.query("select * from t_articles",function(error,results,fields){
if(error) throw error;
res.writeHead(200,{"Content-Type":"text/plain;charset=utf-8;"});
console.log("the result is "+results)
res.end(JSON.stringify(results))
})
}
}).listen(3000)

创建一个mystatic.js文件

var path =require("path");
var fs = require("fs");
var mime = require("Mime"); function mystatic(req,res){
var path_last=path.extname(req.url);
if(req.url=="/"){
fs.readFile(__dirname+"/app"+"/index.html",function(err,data){
res.writeHead(200,{
"content-type":"text/html;charset=utf-8;"
});
res.end(data)
})
} if(path_last){
res.writeHead(200,{"Content-type":mime.getType(path_last)+";charset=utf-8;"}); var url = __dirname+(path_last==".icon"?"":"/app")+req.url;
fs.readFile(url,function(err,data){
res.end(data)
})
}
} module.exports=mystatic;

然后运行server.js启动服务器;

node server.js

每次服务器中的代码修改都需要启动服务器,比较麻烦,但是可以使用nodemon每次帮助自动启动服务器;

具体的看https://www.cnblogs.com/chris-oil/p/6239097.html这篇文章;

向数据库中插入*.json的数据

var mysql      = require('mysql');
var data=require("./data.json");
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'xiaomi',
port: '3307'
}); connection.connect(); for(var i=0;i<data.length;i++){
for(var j=0;j<data[i].list.length;j++){
var sql="insert into product (title,tit,img_url,type,price) values(?,?,?,?,?)";
var obj=data[i].list[j];
connection.query(sql,[data[i].title,obj.tit,obj.img_url,obj.type,obj.price])
}
} connection.end();