nodejs-mysql操作示例

合集下载

解决Node.js使用MySQL...

解决Node.js使用MySQL...

解决Node.js使⽤MySQL...前⾔最近⽤ Node 写⼀个⼩玩意,需要⽤到 MySQL 数据库,现在⽤得最⼴泛的是 mysql 这个库。

然后呢,现在 ORM 这么⽕,⼲脆也上 ORM 吧,正好我也不会可以学习⼀下,于是找到了 Sequelize.js 这个 ORM 库。

发现问题看看 Sequelize 的⽂档,so easy,两分钟搞定~import Sequelize from 'sequelize';let sequelize = new Sequelize('database', 'username', 'password', {host: 'localhost',port: 3306,dialect: 'mysql',pool: {max: 5,min: 0,idle: 10000}});// ...后⾯还有⼀堆懒得贴了运⾏⼀下SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306什么⿁,为什么会出现这个错误呢?我明明设置的是 localhost,为什么会变成 127.0.0.1?解决问题照例先⾕歌,确实发现了很多⼈也遇到了这个问题,解决⽅法⼤概有这么⼏种:1、你丫以为不⽤装 MySQL 就能跑了么?快去装数据库!2、你数据库运⾏了么你?赶紧 /etc/init.d/mysqld start 运⾏起来3、端⼝写错了4、你是不是开启了 skip-networking 这个选项?Remove it !看到这⾥,我反应过来了,因为我的数据库不涉及到远程访问,只要使⽤ Unix socket 通信就够了,于是就启⽤了 skip-networking 让 MySQL 不监听指定端⼝。

先科普⼀下 skip-networking 是什么Do not listen for TCP/IP connections at all. All interaction with mysqld must be made using named pipes or shared memory (on Windows) or Unix socket files (on Unix). This option is highly recommended for systems where only local clients are permitted.翻译⼀下就是:不要监听 TCP/IP 连接。

使用Node.js爬虫存储MySQL数据库

使用Node.js爬虫存储MySQL数据库

使⽤Node.js爬⾍存储MySQL数据库第⼀次使⽤node爬⾍,发帖记录下1.在MySQL中新建book数据库,创建book表2.创建index.js,使⽤npm安装导⼊模块:mysql、axios、cheerio、request、iconv-litelet request = require('request')let iconv = require('iconv-lite')let mysql = require('mysql');let axios = require('axios');let cheerio = require('cheerio');3.测试使⽤node.js连接本地MySQL数据库let mysql = require("mysql");let options = {host:'localhost',port:'3306',//可选,默认是3306user:'root', //数据库名password:'root', //数据库密码//database:'book' //选择连接指定的数据库}// 创建与数据库的连接的对象,传递参数let con = mysql.createConnection(options);// 建⽴连接con.connect((err) => {// 如果建⽴连接失败if (err) {console.log(err);}else {console.log('数据库连接成功');}})// 执⾏数据库语句// 创建库let strSql4 = "create database mall";con.query(strSql4,(err,result) => {console.log(err);console.log(result);})// 创建表:ps这⾥不同编译器可能会因为转义符产⽣报错let strSql5 = 'CREATE TABLE `mall`.`Untitled` (\n' +' `id` int NOT NULL AUTO_INCREMENT,\n' +' `username` varchar(255) NULL,\n' +' `password` varchar(255) NULL,\n' +' `email` varchar(255) NULL,\n' +' PRIMARY KEY (`id`)\n' +');';con.query(strSql5,(err,result) => {console.log(err);console.log(result);})4.找到⽹站所有书籍对应的css标签并解析URL5.根据URL找到css标签解析⼩说的详细信息(书名、作者、简介等)6.完整代码1 let request = require('request')2 let iconv = require('iconv-lite')3 let mysql = require('mysql');4 let axios = require('axios');5 let cheerio = require('cheerio');67 let page = 77013;8var count = 1;9 let options = {10 host:'localhost',11 port:'3306',//可选,默认是330612 user:'root',13 password:'root',14 database:'book'15 }16 let con = mysql.createConnection(options)17 con.connect((err) => {18// 如果建⽴连接失败19if (err) {20 console.log(err);21 }else {22 console.log('数据库连接成功');23 }24 })2526//获取第n个页⾯所有书籍的链接27 async function getPageUrl(callback) {28// let httpUrl = "/txt/" + 69011 + '.html'29 let httpUrl = "/"30 let res = await axios.get(httpUrl)31// console.log(res.data)32 let $ = cheerio.load(res.data)33 $("ul>li>a").each((i,ele) => {34var url = "" + $(ele).attr("href")35// console.log(i);36// console.log(url);37 callback(url)38 })39 }404142 getPageUrl(function (url) {43// console.log(url);44 request({url: url, encoding: null}, (error, res, body) => {45 let html = iconv.decode(body, 'gb2312');46 let $ = cheerio.load(html, {decodeEntities: false})47// 书名48 let bookname = $(".pageMainArea #downInfoTitle").text()49 bookname = bookname.substring(0, bookname.length - 7) 50// 简介51 let bbrief = $(".mainstory #mainSoftIntro p").text()52// ⼩说类型53 let type = $(".downInfoRowL b:nth-child(5) ").text()54// ⼩说类型-value55 let type_value = $(".downInfoRowL").html()56// console.log('打印'+type_value);57if (type_value === null) {58 console.log('打印结束');59return60 }61 type_value = type_value.split("<b>⼩说类型:</b>")[1]62 let type_index = type_stIndexOf('63 \n' +64 '<b>⼩说作者')65 type_value = type_value.substring(0, type_index)66// ⼩说作者67 let author = $(".downInfoRowL b:nth-child(7) ").text()68// ⼩说作者-value69 let author_value = $(".downInfoRowL").html()70 author_value = author_value.split("⼩说作者:</b>")[1]71 let author_index = author_stIndexOf('72 \n' +73 '<b>⼩')74 author_value = author_value.substring(0, author_index) 75// ⼩说⼤⼩76 let size = $(".downInfoRowL b:nth-child(9) ").text()77// ⼩说⼤⼩-value78 let size_value = $(".downInfoRowL").html()79 size_value = size_value.split("⼩说⼤⼩:</b>")[1]80 let size_index = size_stIndexOf('81 \n' +82 '<b>推荐')83 size_value = size_value.substring(0, size_index)84// 更新时间85 let time = $(".downInfoRowL b:nth-child(17) ").text()86// 更新时间-value87 let time_value = $(".downInfoRowL").html()88 time_value = time_value.split("更新时间:</b>")[1]89 let time_index = time_stIndexOf('90 \n' +91 '<b>分享到')92 time_value = time_value.substring(0, time_index)93// 下载94 let download = $("#downAddress").html()95 download = download.split('href=\"')[1]96 let index = stIndexOf('\" target')97 download = download.substring(0, index)98// url链接99 let bookUrl = url;100// console.log(bookname,time,time_value,download,size,size_value,author,author_value,type,type_value);101102103 let arr = [bookname, author_value, type_value, size_value, time_value, bookUrl, download, bbrief];104 console.log(arr);105// 插⼊数据库106 let strSql = "insert into book (bookname,author_value,type_value,size_value,time_value,bookUrl,download,bbrief) values (?,?,?,?,?,?,?,?)" 107 con.query(strSql, arr, (err, result) => {108if (err) {109 console.log(err);110 } else {111 console.log(result);112 }113 })114 })115 });代码到这⾥结束了,后⾯将数据进⾏处理开发图书馆web,如有错误还望多多指教。

nodejs之连接mysql数据库

nodejs之连接mysql数据库

nodejs之连接mysql数据库⼀:demovar mysql = require('mysql');var connection = mysql.createConnection({host : '192.168.0.2',port : '3307',user : 'radar',password: 'radar',database: 'radar'});connection.connect();connection.query('select 1+1 as solution', function (error, results, fields){if (error) throw error;console.log('The solution is: ',results[0].solution);});⼆:封装config.js⽂件module.exports = {host : '192.168.0.2',port : '3307',user : 'radar',password : 'radar',database : 'radar',}db.js⽂件var mysql = require('mysql');var dbConfig = require('./db/config');module.exports = {query : function(sql,param,callback){//每次使⽤的时候要创建链接,数据操作完之后要关闭连接var connection = mysql.createConnection(dbConfig);connection.connect(function(err){if(err){console.log('数据库链接失败');throw err;}//开始数据库操作connection.query(sql, param, function(err,results,fields){if(err){console.log('数据库操作失败');throw err;}//将查询出来的结果返回给回调函数,这个时候就没有必要使⽤错误前置的思想了,因为我们在这个⽂件中已经为错误进⾏了处理,如果数据检索错误,直接会阻塞到这个⽂件中callback && callback(JSON.parse(JSON.stringify(results)), JSON.parse(JSON.stringify(fields)));//results作为数据操作后的结果,fields作为数据库连接的⼀些字段//停⽌连接数据库,必须要在查询数据库之后,不然⼀调⽤这个⽅法,就直接停⽌连接,数据操作就会失败connection.end(function(err){if(err){console.log('关闭数据库连接失败!');throw err;}})})})}}entrance.jsconst express = require('express')const app = express()const bodyParser = require('body-parser')// 我的基础路由⽂件const db = require('./db.js')app.get('/123',function(req,res){db.query('select * from device',(e,r)=>{if(e){res.status(200).json({"status":false,"msg":e,"data":[]});}res.status(200).json({"status":true,"msg":"","data":r});})})// json 解析e(bodyParser.json());e(bodyParser.urlencoded({extended: false}));//设置跨域访问app.all('*', function(req, res, next) {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("X-Powered-By",' 3.2.1')next();});// 暴露公共资源e(express.static('public'))app.listen(8010)console.log('app run port 8010')。

node.js通过Sequelize连接MySQL的方法

node.js通过Sequelize连接MySQL的方法

node.js通过Sequelize连接MySQL的⽅法⼀.通过koa2脚⼿架构建项⽬1.1 安装koa-generator在终端输⼊:$ npm install -g koa-generator1.2 使⽤koa-generator⽣成koa2项⽬$ koa2 HelloKoa2成功创建项⽬后,进⼊项⽬⽬录,并执⾏npm install命令$ cd HelloKoa2$ npm install1.3 启动项⽬在终端输⼊:$ npm start项⽬启动后,默认端⼝号是3000,在浏览器中运⾏可以得到下图的效果说明运⾏成功。

⼆.创建连接2.1刚刚创建的⽂件使⽤webstorm打开新建⼀个db⽬录2.2查看Sequelize⽂档使⽤npm安装Sequelizenpm install --save sequelize你还必须⼿动为所选数据库安装驱动程序选择⼀个⽅法之⼀:# 选择以下之⼀:$ npm install --save pg pg-hstore # Postgres$ npm install --save mysql2$ npm install --save mariadb$ npm install --save sqlite3$ npm install --save tedious # Microsoft SQL Server我这⾥下载得是MySQL22.3连接数据库再刚刚创建得db⽂件加⾥⾯添加**config.js**添加连接代码:module.exports = {dbsMysql: 'mysql://root:123456@localhost:3306/new'//root是数据库管理员账号,‘123546'是密码 3306是端⼝号(MySQL默认是3306) school_admin是数据库名称}继续在db⽂件夹⾥⾯添加mysql.js添加连接以及添加⽇记:const Sequelize = require('sequelize');const mysqlurl = require('./config').dbsMysqlconst sequelize = new Sequelize(mysqlurl, {// 选择⼀种⽇志记录参数logging: console.log // 默认值,显⽰⽇志函数调⽤的第⼀个参数});// //每次启动server刷新数据库// (async ()=>{// await sequelize.sync({ force: true });// })()module.exports = sequelize三.创建模型3.1模型定义在db⽬录下添加models⽂件夹再添加⼀个new2.js定义模型:const { Sequelize, DataTypes, Model } = require('sequelize');const sequelize = require('../mysql');const new2 = sequelize.define('t_new2', {name: {type: DataTypes.STRING,allowNull: false},},{// 这是其他模型参数freezeTableName: true});// 定义的模型是类本⾝module.exports= new2四.添加路由4.1创建new2路由在routes⽂件夹中添加new2.js//引⼊kob得routes模块const router = require('koa-router')()//定义模型为刚刚创建得new2.jslet Model = require("../db/models/new2");//正常来说启动端⼝为http://localhost:3000 添加/new2就可以进⼊new2路由router.prefix('/new1')// 进⼊new2路由以后可以打印this is a users response!router.get('/', function (ctx, next) {ctx.body = 'this is a users response!'})//设置增加add接⼝router.post('/add', async function (ctx, next) {console.log(ctx.request.body)const new2 = await Model.create(ctx.request.body);ctx.body = {code:200,data:new2}})//设置查询find接⼝router.post('/find', async function (ctx, next) {const new2 =await Model.findAll({include: []})console.log(1111)ctx.body = {code: 200,data: new2}})//设置通过id得到所需信息的get接⼝router.post('/get', async function (ctx, next) {// let users = await User.// find({})console.log(ctx.request.body)let new2 = await Model.findOne({// attributes: ['name', 'where']where: {id: ctx.request.body.id}});ctx.body = {code:200,data:new2}})//设置修改update接⼝router.post('/update', async function (ctx, next) {console.log(ctx.request.body)// let pbj = await Model.update({ _id: ctx.request.body._id }, ctx.request.body); let new2 = await Model.update(ctx.request.body, {where: {id: ctx.request.body.id}});ctx.body = new2})//设置删除delete接⼝router.post('/delete', async function (ctx, next) {console.log(ctx.request.body)// 删除所有名为 "Jane" 的⼈await Model.destroy({where: { id: ctx.request.body.id }});ctx.body = 'shibai '})// //每次启动server刷新数据库// (async ()=>{// await sequelize.sync({ force: true });// })()module.exports = router4.2在app.js⾥⾯添加路由//引⼊刚刚创建的new2路由const new2 =require('./routes/new2')//使⽤我们的路由e(new2.routes(),new2.allowedMethods())4.3启动项⽬在数据库中查看5.测试5.1使⽤浏览器查看5.2.使⽤postman测试接⼝测试find接⼝(因为我们写的find⽅法使⽤的post⽅法所以记得将get换成post):测试get接⼝展⽰⼀下最后的⽬录到此这篇关于node.js通过Sequelize 连接MySQL的⽂章就介绍到这了,更多相关node.js连接MySQL内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

nodejs mysql 字符串 科学计数法

nodejs mysql 字符串 科学计数法

nodejs mysql 字符串科学计数法Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,可以让 JavaScript运行在服务器端。

MySQL 是一种关系型数据库管理系统。

科学计数法是一种用科学记数法表示数字的方法,通常以数字和一个指数的形式表示,例如 1.23e4 表示1.23 乘以 10 的 4 次方。

在 Node.js 中使用 MySQL 进行数据库操作时,经常会遇到需要处理科学计数法表示的数据的情况。

在 MySQL 数据库中,科学计数法表示的数据通常以字符串的形式存储,因此在 Node.js 中与 MySQL 交互时,需要注意处理科学计数法字符串的转换和展示。

在 Node.js 中,可以使用 MySQL 模块来连接 MySQL 数据库,进行数据的查询、插入、更新等操作。

在查询数据库时,如果数据中包含科学计数法表示的字符串,可以通过将科学计数法字符串转换为普通数字,再进行操作。

可以使用 JavaScript的 parseFloat() 方法将科学计数法字符串转换为数字,然后再进行需要的操作。

另外,在处理科学计数法字符串时,也需要注意数据的精度,避免精度丢失导致计算结果不准确。

可以通过设置 MySQL 数据库的数据类型,选择合适的数据类型来存储科学计数法表示的数据,以保证数据的精度和准确性。

在 Node.js 中操作 MySQL 数据库时,可以使用一些库来简化操作,如 mysql模块、mysql2 模块等,这些库提供了方便的方法来连接数据库、执行查询、处理结果等操作,可以提高开发效率和准确性。

总的来说,处理 Node.js 中的 MySQL 数据库操作中的科学计数法字符串,需要注意数据的转换和精度的处理,确保数据的准确性和完整性,提高程序的稳定性和可靠性。

通过合理的数据处理和库的选择,可以更好地实现科学计数法字符串的处理和操作。

nodejs和关系型数据库搭配的案例

nodejs和关系型数据库搭配的案例

nodejs和关系型数据库搭配的案例1. 在Node.js中使用MySQL:Node.js可以与MySQL等关系型数据库进行连接,并进行数据的增删改查操作。

例如,假设我们有一个注册用户的功能,用户在网页上填写表单后,将注册的用户信息存储到MySQL数据库中。

javascriptconst mysql = require('mysql');const connection =mysql.createConnection({ host: 'localhost', user: 'root', password:'password', database: 'mydb'});connection.connect(); 注册用户app.post('/register', (req, res) => { const { username, password } = req.body; const sql = `INSERT INTO users (username, password) VALUES ("{username}", "{password}")`; connection.query(sql, (err, result) => { if (err) throw err; res.send('User registeredsuccessfully'); });});app.listen(3000, () => { console.log('Server started on port 3000');});2. 在Node.js中使用MongoDB:Node.js可以与MongoDB 等NoSQL数据库进行连接,并进行数据的增删改查操作。

node mysql sql语句

node mysql sql语句NodeJs是一种服务器端的JavaScript平台,能够充分利用JavaScript的事件驱动、非阻塞I/O等特性实现高性能、可扩展的Web应用程序。

而MySQL则是一种流行的开源数据库管理系统。

当我们使用NodeJs来访问MySQL数据库时,需要考虑如何编写SQL语句。

SQL(Structured Query Language)是一种广泛使用的数据库查询语言,用于在关系型数据库中进行数据操作。

下面将介绍NodeJs中使用MySQL时,如何编写SQL语句。

一、连接MySQL数据库在使用NodeJs连接MySQL数据库之前,需要安装“mysql”模块。

可以使用npm来安装该模块,使用如下命令:npm install mysql在安装完成后,需要在NodeJs程序中引入“mysql”模块。

使用如下命令:const mysql = require('mysql');接下来,需要使用该模块中的“createConnection”方法来创建与MySQL数据库的连接。

创建连接需要提供MySQL数据库的用户名、密码、主机名、端口号等参数。

使用如下命令:const connection = mysql.createConnection({host: 'localhost',user: 'root',password: 'password',database: 'test'});在MySQL数据库中,有多种数据类型,包括整型、浮点型、字符串型、日期型等。

在NodeJs中,可以使用JavaScript中的变量类型来处理不同类型的数据。

二、编写SQL语句编写SQL语句是使用NodeJs访问MySQL数据库的核心部分。

SQL 语句在MySQL数据库中用于进行数据增、删、改、查等操作。

NodeJs中使用MySQL时,可以使用多种方式编写SQL语句。

node+express框架中连接使用mysql(经验总结)

node+express框架中连接使⽤mysql(经验总结)最近在学习node.js,做了⼀个练⼿项⽬,使⽤node.js+express框架,配合mysql数据库和前端vue框架开发⼀个多⼈⽂档编辑系统。

⾸先是环境搭建:node环境下$ npm install -g express-generator$ express -e project进⼊项⽬⽂件根⽬录安装依赖模块$ npm install$ DEBUG=node-blog:* npm start看看项⽬⽬录都有什么看看⽣成的⼯程⽬录⾥⾯都有什么,bin:存放可执⾏⽂件node_modules:存放 package.json 中安装的模块,当你在 package.json 添加依赖的模块并安装后,存放在这个⽂件夹下public:存放 image、css、js 等前端资源⽂件routes:存放路由⽂件views:存放视图⽂件或者说模版⽂件app.js:启动⽂件,或者说⼊⼝⽂件package.json:存储着⼯程的信息及模块依赖,当在 dependencies 中添加依赖的模块时,运⾏npm install ,npm 会检查当前⽬录下的 package.json,并⾃动安装所有指定的模块下⾯开始安装数据库,这⾥我选择的是mysql。

npm install mysql --save-dev安装完毕之后,开始配置数据库。

//mysql配置⽂件mysql = {host: "xx.xxx.xx.xxx", //这是数据库的地址user: "xxx", //需要⽤户的名字password: "xxx", //⽤户密码,如果你没有密码,直接双引号就是database: "xxx" //数据库名字} //好了,这样我们就能连接数据库了module.exports = mysql; //⽤module.exports暴露出这个接⼝,mysql连接池配置://mysql连接池配置⽂件var mysql = require('mysql');var $dbConfig = require('../config/mysql');//注意改成⾃⼰项⽬中mysql配置⽂件的路径// 使⽤连接池,避免开太多的线程,提升性能var pool = mysql.createPool($dbConfig);/*** 对query执⾏的结果⾃定义返回JSON结果*/function responseDoReturn(res, result, resultJSON) {if (typeof result === 'undefined') {res.json({code: '201',msg: 'failed to do'});} else {res.json(result);}};/*** 封装query之sql带不占位符func*/function query(sql, callback) {pool.getConnection(function(err, connection) {connection.query(sql, function(err, rows) {callback(err, rows);//释放链接connection.release();});});}/*** 封装query之sql带占位符func*/function queryArgs(sql, args, callback) {pool.getConnection(function(err, connection) {connection.query(sql, args, function(err, rows) {callback(err, rows);//释放链接connection.release();});});}//exportsmodule.exports = {query: query,queryArgs: queryArgs,doReturn: responseDoReturn}操作数据库的过程⽐较灵活,我是使⽤模块化的思想,将⼀张数据表封装成⼀个模块暴露出去,通过该模块获取这张表的增删改查SQL语句。

Linux下为Node.js程序配置MySQL或Oracle数据库的方法

这篇文章主要介绍了Linux下为Node.js程序配置MySQL或Oracle数据库的方法,这里默认已经装配好了Node环境然后我们利用npm包管理工具来进行配置,需要的朋友可以参考下mysql使用安装mysql 模块:在安装根目录cmd命令行执行命令&nbsp;npm install mysql安装成功后、mysql数据库表已存在的情况下。

在nodejs根目录新建mysql.js:var sys = require('util');&nbsp;var mysql=require('mysql');&nbsp;console.log('正在连接MySQL...');&nbsp;var http = require("http");&nbsp;var server=http.createServer(function(request, response) {&nbsp;&nbsp; response.writeHead(200, {"Content-Type": "text/html;charset:utf-8"}); &nbsp;&nbsp; response.write("&lt;!doctype html&gt;&lt;html&gt;&lt;meta charset='utf-8'/&gt;");&nbsp;&nbsp; &nbsp;var client = mysql.createConnection({'host':'localhost','port':3306,'user':'testmysql','password':'123456'});&nbs p;&nbsp; clientConnectionReady = function(client)&nbsp;&nbsp; {&nbsp;&nbsp; &nbsp; client.query('use test', function(error, results) {&nbsp;&nbsp; &nbsp; &nbsp; if(error) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; console.log('ClientConnectionReady Error: ' + error.message);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; client.end();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp;&nbsp; &nbsp; &nbsp; }else{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; response.write("nodejs 服务器已经开始工作...&lt;br/&gt;");&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; response.write("已经连接上MySQL....&lt;br/&gt;");&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; clientReady(client);&nbsp;&nbsp; &nbsp; });&nbsp;&nbsp; };&nbsp;&nbsp; clientReady = function(client) {&nbsp;&nbsp; &nbsp; var values = ['不错啊'];&nbsp;&nbsp; &nbsp; client.query('insert into nodemysql set names = :1', values,&nbsp;&nbsp; &nbsp; &nbsp; function(error, results) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if(error) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("ClientReady Error: " + error.message);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; client.end();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; console.log('Inserted: ' + results.affectedRows + ' row.');&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; console.log('Id inserted: ' + results.insertId);&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; );&nbsp;&nbsp; &nbsp; getData(client);&nbsp;&nbsp; }&nbsp;&nbsp; getData = function(client) {&nbsp;&nbsp; &nbsp; client.query(&nbsp;&nbsp; &nbsp; &nbsp; 'select * from nodemysql',&nbsp;&nbsp; &nbsp; &nbsp; function selectCb(error, results, fields) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (error) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('GetData Error: ' + error.message);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; client.end();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp;var data = '';&nbsp;&nbsp; &nbsp; &nbsp; for(var i=0; i&lt;results.length; i++){&nbsp;&nbsp; &nbsp; &nbsp; var firstResult = results[i];&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data += 'id: ' + firstResult['id']+' &nbsp;name: ' + firstResult['names']+"&lt;br/&gt;";&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;response.write(data); &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;response.write("关闭MySQL连接...");&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;response.write("&lt;/html&gt;");&nbsp;&nbsp; &nbsp; &nbsp; response.end();&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; );&nbsp;&nbsp; &nbsp; client.end();&nbsp;&nbsp; };&nbsp;&nbsp; clientConnectionReady(client);&nbsp;});&nbsp;server.listen(8033,"127.0.0.1");&nbsp;var sys = require("util");&nbsp;sys.puts("Server running at http://localhost:8033/"); &nbsp;&nbsp;运行node mysql.js &nbsp;。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

nodejs - mysql操作示例
// demo-mysql.js
var mysql = require('mysql');
var client = new mysql.Client();

client.host = 'localhost';
client.user = 'root';
client.password = '123456';

client.query('show databases', function(err, rows, fields) {
if (err) { // error happend
console.log(err);
} else {
console.log(rows);
}
client.end();
});

执行:

#node demo-mysql.js

如果没有安装mysql模块,可用npm安装:
#npm install mysql

#npm install -g mysql

带-g参数会安装在系统默认的模块目录,否则安装在当装目录下。
如果已经安装了mysql模块,还提示找不到,那就是模块路径的问题,可在工作目录做个软链接或
者加到环境变量里面。

#ln -s $PREFIX/bin/node_modules node_modules

相关文档
最新文档