Nodejs操作MySQL-增删改查
时间:2023-02-22
浏览:478
作者:佚名
本篇文章向大家介绍《Nodejs操作MySQL-增删改查》,主要包括MySQL、Node.js,具有一定的参考价值,需要的朋友可以参考一下。
先安装npm模块项目
npm init
安装mysql
npm install mysql --save
Nodejs 连接msyql
// 导入mysql
const mysql = require('mysql');
// 连接mysql
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
port: '3306',
database: 'test'
});
connection.connect();
// 结束连接
connection.end();
增
// 引入mysql
const mysql = require('mysql');
// 连接myql
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
port: '3306',
database: 'test',
});
connection.connect();
// 插入语句
let addSql = "insert into article (title, author, date) values (?, ?, now())";
let addSqlParams = ['Today is noce', 'Bob'];
// 执行插入语句
connection.query(addSql, addSqlParams, (err, result) => {
if (err) {
throw err;
}
// 插入成功输出
console.log('插入成功');
console.log(result);
});
// 断开连接msyql
connection.end();
删
// 引入mysql
const mysql = require('mysql');
// 连接mysql
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
port: '3306',
database: 'test'
});
connection.connect();
// 删除语句
let sql = "delete from article where id = 10";
// 执行删除语句
connection.query(sql, (err, data) => {
if (err) {
throw err;
}
// 执行成功
console.log('delete success!');
console.log(data);
});
// 断开连接msyql
connection.end();
改
// 导入mysql
const mysql = require('mysql');
// 连接mysql
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
port: '3306',
database: 'test'
});
connection.connect();
// 更新语句
let modSql = "update article set title = ?, author = ? where id like ?";
let modSqlParams = ['今晚学习nodejs', '一波万波', 12];
// 执行更新语句
connection.query(modSql, modSqlParams, (err, data) => {
if (err) {
throw err;
}
console.log('upload success!');
console.log(data)
});
connection.end();
查
// 导入mysql
const mysql = require('mysql');
// 连接mysql
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
port: '3306',
database: 'test',
});
connection.connect();
// 查询语句
let sql = 'SELECT * FROM article';
// 执行查询语句
connection.query(sql, (err, data) => {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
return;
}
// 查询成功
console.log(data);
});
connection.end();
今天关于《Nodejs操作MySQL-增删改查》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
11.27
11.27
11.27
11.27
热门专题
