Node使用native方法连接mysql数据库(async()=>{//链接数据库constmysql=require('mysql2/promise');//npmimysql2constcfg={host:'localhost',user:'root',password:';he%0f_,ljyW',database:'izengx',}constconnection=awaitmysql.createConnection(cfg);//创建一个新表testsletret=awaitconnection.execute(`CREATETABLEIFNOTEXISTStests(idINTNOTNULLAUTO_INCREMENT,messageVARCHAR(45)NULL,PRIMARYKEY(id))`)console.log('create',ret);//新数据ret=等待连接。execute(`INSERTINTOtests(message)VALUE(?)`,['newData'])console.log('newdata',ret);const[rows,fields]=awaitconnection.execute(`SELECT*FROMtests`)console.log('Querydata',rows);})()使用数据库中间件(ORM):sequelize连接并操作数据库(async()=>{//使用数据库中间件(ORM):sequelize连接并操作数据库//1.使用Sequelize时,生成的表名会自动加上复数,比如fruit->fruits//2.自动生成主键id,自增(缺点是合并old和fruits时新数据,id又从1开始,会有重叠)constSequelize=require('sequelize');constsequelize=newSequelize('izengx','root',';he%0f_,ljyW',{host:'localhost',dialect:'mysql',operatorsAliases:false,})constFruit=sequelize.define('Fruit',{name:{type:Sequelize.STRING(20),allowNull:false,},price:{type:Sequelize.FLOAT,allowNull:false},stock:{type:Sequelize.INTEGER,defaultValue:0}})//同步数据库letret=awaitFruit.sync();//添加一条数据ret=awaitFruit.create({name:'apple',price:3.5})//更新数据awaitFruit.update({price:4,},{where:{name:'banana',}})//查询ret=awaitFruit.findAll();//查询指定范围内的数据constOp=Sequelize.Op;opRet=awaitFruit.findAll({where:{price:{[Op.gt]:3,[Op.lt]:5,}}})控制台。日志('搜索:'+JSON.stringify(opRet));})()
