天天看點

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', '一波萬波', ];

// 執行更新語句
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();