標籤:操作 title ini mys oda insert tle div int
先安裝npm模組項目
npm init
安裝mysql
npm install mysql --save
Nodejs 串連msyql
// 匯入mysqlconst mysql = require(‘mysql‘);// 串連mysqlconst connection = mysql.createConnection({ host: ‘127.0.0.1‘, user: ‘root‘, password: ‘password‘, port: ‘3306‘, database: ‘test‘});connection.connect();// 結束串連connection.end();
增
// 引入mysqlconst mysql = require(‘mysql‘);// 串連myqlconst 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);});// 中斷連線msyqlconnection.end();
刪
// 引入mysqlconst mysql = require(‘mysql‘);// 串連mysqlconst 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);});// 中斷連線msyqlconnection.end();
改
// 匯入mysqlconst mysql = require(‘mysql‘);// 串連mysqlconst 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();
查
// 匯入mysqlconst mysql = require(‘mysql‘);// 串連mysqlconst 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 - 增刪改查