Home > Web Front-end > JS Tutorial > Nodejs simple method to access and operate mysql database

Nodejs simple method to access and operate mysql database

不言
Release: 2018-07-02 16:24:09
Original
1461 people have browsed it

This article mainly introduces the simple method of nodejs to access and operate mysql database. It analyzes the related operation skills of nodejs to create mysql connection, execute sql statement and close the connection in the form of examples. Friends who need it can refer to it

The example in this article describes how nodejs can simply access and operate the mysql database. Share it with everyone for your reference, the details are as follows:

var mysql = require('mysql'); //调用MySQL模块 mysql模块要安装 $ npm install mysql
//创建一个connection
var connection = mysql.createConnection({
  host   : '127.0.0.1',    //主机
  user   : 'root',        //MySQL认证用户名
  password : '',    //MySQL认证用户密码
  port: '3306',          //端口号
  database:''   //数据库名
});
//创建一个connection
connection.connect(function(err){
  if(err){
    console.log('[query] - :'+err);
    return;
  }
  console.log('[connection connect] succeed!');
});
//执行SQL语句
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) {
    console.log('[query] - :'+err);
    return;
  }
  console.log('The solution is: ', rows[0].solution);
});
//关闭connection
connection.end(function(err){
  if(err){
    return;
  }
  console.log('[connection end] succeed!');
});
Copy after login

Note: nodejs does not need to set the encoding format of the database when operating the database set names utf8

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Analysis of Http module of Nodejs

How to merge two complex objects in Node.js Introduction

nodejs method to implement bigpipe asynchronous loading of pages

The above is the detailed content of Nodejs simple method to access and operate mysql database. 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