Home > Web Front-end > JS Tutorial > Node.js method example for connecting to MySQL

Node.js method example for connecting to MySQL

小云云
Release: 2018-03-02 11:30:44
Original
1587 people have browsed it

In this article, we mainly introduce how to use Node.js to connect to MySQL and operate the database. The Websites table SQL file used in this tutorial: websites.sql, I hope it can be helpful to everyone.

Installing the driver

This tutorial uses Taobao’s customized cnpm command for installation:

$ cnpm install mysql
Copy after login

Connect to the database

Modify in the following examples according to your actual situation Configure and modify the database user name, password and database name:

test.js file code:

var mysql      = require('mysql');
var connection = mysql.createConnection
({  host     : 'localhost',  user     :
 'root',  password : '123456',  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);}
   );
Copy after login

Execute the following command and the output will be:

$ node test.js
The solution is: 2
Copy after login

数据库连接参数说明:

参数描述
host主机地址 (默认:localhost)
user用户名
password密码
port端口号 (默认:3306)
database数据库名
charset连接字符集(默认:'UTF8_GENERAL_CI',注意字符集的字母都要大写)
localAddress此IP用于TCP连接(可选)
socketPath连接到unix域路径,当使用 host 和 port 时会被忽略
timezone时区(默认:'local')
connectTimeoutConnection timeout (default: no limit; unit: milliseconds)
stringifyObjectsWhether to serialize objects
typeCastWhether to convert column values ​​into local JavaScript type values ​​(default: true)
queryFormatCustom query statement formatting method
supportBigNumbersWhen the database supports bigint or decimal type columns, you need to set this option to true (default: false)
bigNumberStringssupportBigNumbers and bigNumberStrings enable forcing bigint or decimal columns to be returned as JavaScript string types (default: false)
dateStringsForce timestamp, datetime, and data types to be returned as string types instead of JavaScript Date types (default: false)
debugEnable debugging ( Default: false)
multipleStatementsWhether to allow multiple MySQL statements in one query (default: false)
flags is used to modify the connection flags
sslUse the ssl parameter (the same format as the crypto.createCredenitals parameter) or a ssl configuration file name containing The string, currently only bundles the Amazon RDS configuration file

更多说明可参见:https://github.com/mysqljs/mysql


数据库操作( CURD )

在进行数据库操作前,你需要将本站提供的 Websites 表 SQL 文件websites.sql 导入到你的 MySQL 数据库中。

本教程测试的 MySQL 用户名为 root,密码为 123456,数据库为 test,你需要根据自己配置情况修改。

查询数据

将上面我们提供的 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();
Copy after login

执行以下命令输出就结果为:

$ 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' } ]------------------------------------------------------------
Copy after login

插入数据

我们可以向数据表 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();
Copy after login

执行以下命令输出就结果为:

$ node test.js--------------------------INSERT----------------------------INSERT ID: OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 6,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0 }-----------------------------------------------------------------
Copy after login

执行成功后,查看数据表,即可以看到添加的数据:

更新数据

我们也可以对数据库的数据进行修改:

更新数据

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-----------------------------------------------------------------
Copy after login

执行成功后,查看数据表,即可以看到更新的数据:

删除数据

我们可以使用以下代码来删除 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();
Copy after login

执行以下命令输出就结果为:

--------------------------DELETE----------------------------DELETE affectedRows 1-----------------------------------------------------------------
Copy after login

执行成功后,查看数据表,即可以看到 id=6 的数据已被删除:

相关推荐:

PHP 使用 ODBC 连接 Mysql 数据库_PHP教程

php 连接 mysql数据库操作类_PHP教程

node.js 开发指南 – Node.js 连接 MySQL 并进行数据库操作_node.js

The above is the detailed content of Node.js method example for connecting to MySQL. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template