Home >Web Front-end >JS Tutorial >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
Modify in the following examples according to your actual situation Configure and modify the database user name, password and database name:
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
在进行数据库操作前,你需要将本站提供的 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!