Node.js method example for connecting to MySQL
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
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);} );
Execute the following command and the output will be:
$ node test.js The solution is: 2
数据库连接参数说明:
参数 | 描述 |
---|---|
host | 主机地址 (默认:localhost) |
user | 用户名 |
password | 密码 |
port | 端口号 (默认:3306) |
database | 数据库名 |
charset | 连接字符集(默认:'UTF8_GENERAL_CI',注意字符集的字母都要大写) |
localAddress | 此IP用于TCP连接(可选) |
socketPath | 连接到unix域路径,当使用 host 和 port 时会被忽略 |
timezone | 时区(默认:'local') |
connectTimeout | Connection timeout (default: no limit; unit: milliseconds) |
stringifyObjects | Whether to serialize objects |
typeCast | Whether to convert column values into local JavaScript type values (default: true) |
queryFormat | Custom query statement formatting method |
supportBigNumbers | When the database supports bigint or decimal type columns, you need to set this option to true (default: false) |
bigNumberStrings | supportBigNumbers and bigNumberStrings enable forcing bigint or decimal columns to be returned as JavaScript string types (default: false) |
dateStrings | Force timestamp, datetime, and data types to be returned as string types instead of JavaScript Date types (default: false) |
debug | Enable debugging ( Default: false) |
multipleStatements | Whether to allow multiple MySQL statements in one query (default: false) |
flags | is used to modify the connection flags |
ssl | Use 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();
执行以下命令输出就结果为:
$ 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 插入数据:
插入数据
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 }-----------------------------------------------------------------
执行成功后,查看数据表,即可以看到添加的数据:
更新数据
我们也可以对数据库的数据进行修改:
更新数据
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-----------------------------------------------------------------
执行成功后,查看数据表,即可以看到更新的数据:
删除数据
我们可以使用以下代码来删除 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 的数据已被删除:
相关推荐:
PHP 使用 ODBC 连接 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.
