node. JS interacts with MySQL with many libraries felixge/node-mysql commonly used
cnpm i mysql--save dev
1, open MySQL must have, I use the wamp. Navicat Premium for visualization
var mysql = require (' mysql '); // call the MySQL module var db_config = {host: ' localhost ', // host User: ' Root ', mysql authenticated user name password: ", // mysql authenticated user password port: ' 3306 ', // port number through php.in you can see database: ' nodetest ', // database name charset: ' Utf8_general_ci ' // utf8_general_ci }; var connection;
It has a lot of options.
Host: Hosts address (default: localhost)
User: Username
Password: password
Port: Port number (default: 3306)
Database: DB name
CharSet: Connection Character Set (default: ' Utf8_general_ci ', note character set letters are capitalized)
LocalAddress: This IP is used for TCP connections (optional)
Socketpath: Connecting to a UNIX domain path that is ignored when host and Port are used
TimeZone: Time zone (default: ' Local ')
ConnectTimeout: Connection Timeout (default: No Limit; units: milliseconds)
Stringifyobjects: Whether to serialize the object (default: ' false '; security-related https://github.com/felixge/node-mysql/issues/501)
Typecast: Whether to convert column values to local JavaScript type values (default: TRUE)
Queryformat: Custom Query statement formatting method Https://github.com/felixge/node-mysql#custom-format
Supportbignumbers: You need to set this option to True when the database supports bigint or decimal type columns (default: false)
Bignumberstrings:supportbignumbers and bignumberstrings enable force bigint or decimal columns to be returned as JavaScript string types (default: false)
Datestrings: Forces the Timestamp,datetime,data type to be returned as a string type instead of a JavaScript date type (default: false)
Debug: Turn on Debug (default: false)
Multiplestatements: Whether to make a query with multiple MySQL statements (default: false)
Flags: Used to modify connection flags, more details: https://github.com/felixge/node-mysql#connection-flags
SSL: Using the SSL parameter (one to the crypto.createcredenitals parameter format) or a string containing the SSL profile name, only the configuration file for Amazon RDS is currently bundled
2. Connect MySQL
When you connect to MySQL, sometimes you restart MySQL how to automatically link it?
function Handledisconnect () { connection = mysql.createconnection (db_config); Connection.connect (function (err) { if (err) { console.log ("For wire break:" + new Date ()); SetTimeout (Handledisconnect, 2000); 2 seconds to re-connect once return; } Console.log ("Connection succeeded"); }); Connection.on (' Error ', function (err) { console.log (' db error ', err); if (Err.code = = = ' Protocol_connection_lost ') { handledisconnect (); } else { throw err; } });} Handledisconnect ();
All codes are as follows:
Node link mysql (auto link)