Home > Web Front-end > JS Tutorial > body text

How to access and operate mysql database with nodejs

小云云
Release: 2018-03-16 09:16:50
Original
1933 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. I hope it can help. to everyone.


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

Related recommendations:

PHP operates MySQL database

php operates some commonly used built-in functions of mysql database

Introduction to using node to operate mysql database instance


The above is the detailed content of How to access and operate mysql database with nodejs. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!