【Nodejs】使用nodejs链接mysql实现增删查改

【Nodejs】使用nodejs链接mysql实现增删查改

使用npm 安装mysql,命令行输入npm install mysql

// db.js
// 数据库配置信息

module.exports = {
	host:		'localhost'	,
	port:		'3306',
	database:	'database',
	user:		'root',
	password:	'root'
}
// conn_get.js
// 查询数据

const mysql = require('mysql')
const dbConfig = require('./db')

var connection = mysql.createConnection(dbConfig) 
connect.connect()
var getSql = 'SELECT * FROM tablename'
connection.query(getSql, function(err,result){
	if(err){
		console.log('[SELECT ERROR] -',err.message)
		return
	}

	console.log(result)
})

// 关闭数据库连接
connection.end()
// conn_add.js
// 插入数据
const mysql = require('mysql')
const dbConfig = require('./db')

// 打开连接
var connection = mysql.createConnection(dbConfig) 
connect.connect()

// 要插入的数据
var addSql = 'INSERT INTO  article(Id,title,url,img) VALUES(0,?,?,?)''
var addSqlParams = ['使用Nodejs 连接 mysql', 'http://xxxx.com/article/xxx','http://www.xxx.com/img/02645646.jpg']

// 插入
connection.query(addSql,addSqlParams, function(err,result){
	if(err){
		console.log('[INSERT ERROR] - ',err.message)
		return
	}
	console.log('INSERT ID:',result)
})

// 关闭数据库连接
connection.end()
// conn_update.js
// 修改数据
const mysql = require('mysql')
const dbConfig = require('./db')

// 打开连接
var connection = mysql.createConnection(dbConfig) 
connect.connect()

// 要修改的数据
var modSql = 'UPDATE  article SET title = ?, url = ? WHERE Id = ?'
var modSqlParams = ['【记】使用Nodejs 连接 mysql', 'http://xxxx.com/article/xxx','http://www.xxx.com/img/02649413.jpg']

// 修改
connection.query(modSql,modSqlParams, function(err,result){
	if(err){
		console.log('[更新失败] - ',err.message)
		return
	}
	console.log('更新成功:',result.affectedRows)
})

// 关闭数据库连接
connection.end()
// conn_del.js
// 删除数据
const mysql = require('mysql')
const dbConfig = require('./db')

// 打开连接
var connection = mysql.createConnection(dbConfig) 
connect.connect()

// 要删除的数据
var delSql = 'DELECT FROM acticle where id = 1'

// 删除
connection.query(modSql, function(err,result){
	if(err){
		console.log('[删除失败] - ',err.message)
		return
	}
	console.log('成功删除:',result.affectedRows)
})

// 关闭数据库连接
connection.end()

参考:
Nodejs连接mysql的增、删、改、查操作
Node.js 连接 MySQL

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值