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();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值