Table of Contents
Connect to the database
test.js file code:
数据库连接参数说明:
数据库操作( CURD )
查询数据
插入数据
更新数据
删除数据
Home Web Front-end JS Tutorial Node.js method example for connecting to MySQL

Node.js method example for connecting to MySQL

Mar 02, 2018 am 11:30 AM
javascript mysql node.js

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

See all articles