1、安装驱动
使用 npm 进行安装 mysql
$ npm install mysql
2、连接数据库
在以下实例中根据你的实际配置修改数据库用户名、及密码及数据库名:
test.js 文件
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456789',
database : 'test'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
执行以下命令输出结果为:
$ node test.js
The solution is: 2
3、数据库操作( CURD )
在进行数据库操作前,你需要提供 Websites 表 SQL 文件websites.sql 导入到你的 MySQL 数据库中。
/*
Navicat MySQL Data Transfer
Source Server : 127.0.0.1
Source Server Version : 50621
Source Host : localhost
Source Database : RUNOOB
Target Server Version : 50621
File Encoding : utf-8
Date: 08/10/2023 16:44:07 PM
*/
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `websites`
-- ----------------------------
DROP TABLE IF EXISTS `websites`;
CREATE TABLE `websites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL DEFAULT '' COMMENT '站点名称',
`url` varchar(255) NOT NULL DEFAULT '',
`alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa 排名',
`country` char(10) NOT NULL DEFAULT '' COMMENT '国家',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of `websites`
-- ----------------------------
BEGIN;
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');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
这里测试的 MySQL 用户名为 root,密码为 123456,数据库为 test,需要根据自己配置情况修改。
(1)查询数据
将上面我们提供的 SQL 文件导入数据库后,执行以下代码即可查询出数据
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
port: '3306',
database: 'test'
});
connection.connect();
var sql = 'SELECT * FROM websites';
//查
connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
console.log('--------------------------SELECT----------------------------');
console.log(result);
console.log('------------------------------------------------------------\n\n');
});
connection.end();
执行以下命令输出就结果为
$ 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' } ] ------------------------------------------------------------
(2)插入数据
可以向数据表 websties 插入数据
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
port: '3306',
database: 'test'
});
connection.connect();
var addSql = 'INSERT INTO websites(Id,name,url,alexa,country) VALUES(0,?,?,?,?)';
var addSqlParams = ['菜鸟工具', 'https://c.runoob.com','23453', 'CN'];
//增
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
console.log('--------------------------INSERT----------------------------');
//console.log('INSERT ID:',result.insertId);
console.log('INSERT ID:',result);
console.log('-----------------------------------------------------------------\n\n');
});
connection.end();
执行以下命令输出就结果为
$ node test.js --------------------------INSERT---------------------------- INSERT ID: OkPacket { fieldCount: 0, affectedRows: 1, insertId: 6, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0 } -----------------------------------------------------------------
(3)更新数据
可以对数据库的数据进行修改
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
port: '3306',
database: 'test'
});
connection.connect();
var modSql = 'UPDATE websites SET name = ?,url = ? WHERE Id = ?';
var modSqlParams = ['菜鸟移动站', 'https://m.runoob.com',6];
//改
connection.query(modSql,modSqlParams,function (err, result) {
if(err){
console.log('[UPDATE ERROR] - ',err.message);
return;
}
console.log('--------------------------UPDATE----------------------------');
console.log('UPDATE affectedRows',result.affectedRows);
console.log('-----------------------------------------------------------------\n\n');
});
connection.end();
执行以下命令输出就结果为:
--------------------------UPDATE----------------------------
UPDATE affectedRows 1
-----------------------------------------------------------------
执行成功后,查看数据表,即可以看到更新的数据
(4)删除数据
可以使用以下代码来删除 id 为 6 的数据
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
port: '3306',
database: 'test'
});
connection.connect();
var delSql = 'DELETE FROM websites where id=6';
//删
connection.query(delSql,function (err, result) {
if(err){
console.log('[DELETE ERROR] - ',err.message);
return;
}
console.log('--------------------------DELETE----------------------------');
console.log('DELETE affectedRows',result.affectedRows);
console.log('-----------------------------------------------------------------\n\n');
});
connection.end();
执行以下命令输出就结果为
--------------------------DELETE---------------------------- DELETE affectedRows 1 -----------------------------------------------------------------
执行成功后,查看数据表,即可以看到 id=6 的数据已被删除