Nodejs操作MySQL - 增删改查

Posted Blog - Liang Fengbo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nodejs操作MySQL - 增删改查相关的知识,希望对你有一定的参考价值。

先安装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 - 增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Nodejs mysql 数据库增删改查 操作

Nodejs操作MySQL之增删改查

NodeJS中MySql的增删改查操作

nodejs利用express操作mysql增删改查

基于nodejs+express+mysql+webstorm+html的 增删改查

nodejs连接数据库的增删改查