本教程使用了淘寶定製的 cnpm 命令進行安裝:html
$ cnpm install mysql
在如下實例中修改根據你的實際配置修改數據庫用戶名、及密碼及數據庫名:node
1 var mysql = require('mysql'); 2 var connection = mysql.createConnection({ 3 host : 'localhost', 4 user : 'root', 5 password : '123456', 6 database : 'test' 7 }); 8 9 connection.connect(); 10 11 connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { 12 if (error) throw error; 13 console.log('The solution is: ', results[0].solution); 14 });
參數 | 描述 |
---|---|
host | 主機地址 (默認:localhost) |
user | 用戶名 |
password | 密碼 |
port | 端口號 (默認:3306) |
database | 數據庫名 |
charset | 鏈接字符集(默認:'UTF8_GENERAL_CI',注意字符集的字母都要大寫) |
localAddress | 此IP用於TCP鏈接(可選) |
socketPath | 鏈接到unix域路徑,當使用 host 和 port 時會被忽略 |
timezone | 時區(默認:'local') |
connectTimeout | 鏈接超時(默認:不限制;單位:毫秒) |
stringifyObjects | 是否序列化對象 |
typeCast | 是否將列值轉化爲本地JavaScript類型值 (默認:true) |
queryFormat | 自定義query語句格式化方法 |
supportBigNumbers | 數據庫支持bigint或decimal類型列時,須要設此option爲true (默認:false) |
bigNumberStrings | supportBigNumbers和bigNumberStrings啓用 強制bigint或decimal列以JavaScript字符串類型返回(默認:false) |
dateStrings | 強制timestamp,datetime,data類型以字符串類型返回,而不是JavaScript Date類型(默認:false) |
debug | 開啓調試(默認:false) |
multipleStatements | 是否許一個query中有多個MySQL語句 (默認:false) |
flags | 用於修改鏈接標誌 |
ssl | 使用ssl參數(與crypto.createCredenitals參數格式一至)或一個包含ssl配置文件名稱的字符串,目前只捆綁Amazon RDS的配置文件 |
更多說明可參見:https://github.com/mysqljs/mysqlmysql
1 /* 2 Navicat MySQL Data Transfer 3 4 Source Server : 127.0.0.1 5 Source Server Version : 50621 6 Source Host : localhost 7 Source Database : RUNOOB 8 9 Target Server Version : 50621 10 File Encoding : utf-8 11 12 Date: 05/18/2016 11:44:07 AM 13 */ 14 15 SET NAMES utf8; 16 SET FOREIGN_KEY_CHECKS = 0; 17 18 -- ---------------------------- 19 -- Table structure for `websites` 20 -- ---------------------------- 21 DROP TABLE IF EXISTS `websites`; 22 CREATE TABLE `websites` ( 23 `id` int(11) NOT NULL AUTO_INCREMENT, 24 `name` char(20) NOT NULL DEFAULT '' COMMENT '站點名稱', 25 `url` varchar(255) NOT NULL DEFAULT '', 26 `alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa 排名', 27 `country` char(10) NOT NULL DEFAULT '' COMMENT '國家', 28 PRIMARY KEY (`id`) 29 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; 30 31 -- ---------------------------- 32 -- Records of `websites` 33 -- ---------------------------- 34 BEGIN; 35 INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA'), ('2', '淘寶', 'https://www.taobao.com/', '13', 'CN'), ('3', '菜鳥教程', 'http://www.runoob.com/', '4689', 'CN'), ('4', '微博', 'http://weibo.com/', '20', 'CN'), ('5', 'Facebook', 'https://www.facebook.com/', '3', 'USA'); 36 COMMIT; 37 38 SET FOREIGN_KEY_CHECKS = 1;
1 var mysql = require('mysql'); 2 3 var connection = mysql.createConnection({ 4 host : 'localhost', 5 user : 'root', 6 password : '123456', 7 port: '3306', 8 database: 'test', 9 }); 10 11 connection.connect(); 12 13 var sql = 'SELECT * FROM websites'; 14 //查 15 connection.query(sql,function (err, result) { 16 if(err){ 17 console.log('[SELECT ERROR] - ',err.message); 18 return; 19 } 20 21 console.log('--------------------------SELECT----------------------------'); 22 console.log(result); 23 console.log('------------------------------------------------------------\n\n'); 24 }); 25 26 connection.end();
將上面咱們提供的 SQL 文件導入數據庫後,執行如下代碼便可查詢出數據:git
$ node test.js --------------------------SELECT---------------------------- [ RowDataPacket { id: 1, name: 'Google', url: 'https://www.google.cm/', alexa: 1, country: 'USA' }, RowDataPacket { id: 2, name: '淘寶', url: 'https://www.taobao.com/', alexa: 13, country: 'CN' }, RowDataPacket { id: 3, name: '菜鳥教程', url: 'http://www.runoob.com/', alexa: 4689, country: 'CN' }, RowDataPacket { id: 4, name: '微博', url: 'http://weibo.com/', alexa: 20, country: 'CN' }, RowDataPacket { id: 5, name: 'Facebook', url: 'https://www.facebook.com/', alexa: 3, country: 'USA' } ] ------------------------------------------------------------
咱們能夠向數據表 websties 插入數據:github
1 var mysql = require('mysql'); 2 3 var connection = mysql.createConnection({ 4 host : 'localhost', 5 user : 'root', 6 password : '123456', 7 port: '3306', 8 database: 'test', 9 }); 10 11 connection.connect(); 12 13 var addSql = 'INSERT INTO websites(Id,name,url,alexa,country) VALUES(0,?,?,?,?)'; 14 var addSqlParams = ['菜鳥工具', 'https://c.runoob.com','23453', 'CN']; 15 //增 16 connection.query(addSql,addSqlParams,function (err, result) { 17 if(err){ 18 console.log('[INSERT ERROR] - ',err.message); 19 return; 20 } 21 22 console.log('--------------------------INSERT----------------------------'); 23 //console.log('INSERT ID:',result.insertId); 24 console.log('INSERT ID:',result); 25 console.log('-----------------------------------------------------------------\n\n'); 26 }); 27 28 connection.end();
$ node test.js --------------------------INSERT---------------------------- INSERT ID: OkPacket { fieldCount: 0, affectedRows: 1, insertId: 6, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0 } -----------------------------------------------------------------
執行成功後,查看數據表,便可以看到添加的數據:web
咱們也能夠對數據庫的數據進行修改:sql
1 var mysql = require('mysql'); 2 3 var connection = mysql.createConnection({ 4 host : 'localhost', 5 user : 'root', 6 password : '123456', 7 port: '3306', 8 database: 'test', 9 }); 10 11 connection.connect(); 12 13 var modSql = 'UPDATE websites SET name = ?,url = ? WHERE Id = ?'; 14 var modSqlParams = ['菜鳥移動站', 'https://m.runoob.com',6]; 15 //改 16 connection.query(modSql,modSqlParams,function (err, result) { 17 if(err){ 18 console.log('[UPDATE ERROR] - ',err.message); 19 return; 20 } 21 console.log('--------------------------UPDATE----------------------------'); 22 console.log('UPDATE affectedRows',result.affectedRows); 23 console.log('-----------------------------------------------------------------\n\n'); 24 }); 25 26 connection.end();
--------------------------UPDATE---------------------------- UPDATE affectedRows 1 -----------------------------------------------------------------
執行成功後,查看數據表,便可以看到更新的數據:數據庫
咱們可使用如下代碼來刪除 id 爲 6 的數據:express
1 var mysql = require('mysql'); 2 3 var connection = mysql.createConnection({ 4 host : 'localhost', 5 user : 'root', 6 password : '123456', 7 port: '3306', 8 database: 'test', 9 }); 10 11 connection.connect(); 12 13 var delSql = 'DELETE FROM websites where id=6'; 14 //刪 15 connection.query(delSql,function (err, result) { 16 if(err){ 17 console.log('[DELETE ERROR] - ',err.message); 18 return; 19 } 20 21 console.log('--------------------------DELETE----------------------------'); 22 console.log('DELETE affectedRows',result.affectedRows); 23 console.log('-----------------------------------------------------------------\n\n'); 24 }); 25 26 connection.end();
--------------------------DELETE---------------------------- DELETE affectedRows 1 -----------------------------------------------------------------
執行成功後,查看數據表,便可以看到 id=6 的數據已被刪除:npm