Home >Web Front-end >JS Tutorial >How to implement node connection to mysql
This time I will bring you how to connect node to mysql. What are the precautions to connect node to mysql? The following is a practical case, let’s take a look.
Mysql basic commandsChange root password 123 to 1234mysqladmin -u root -p 123 password 1234;Display database
show databases;
Create database, for example:
create database database_test create database [database];Use the database, for example:
use database_test use [database];Delete the database, for example:
drop database database_test drop database [database];Create a table, for example:
create table_test(name char(10) not null,age int(4)) create table <table>(<field><type>);
Insert data, For example:
insert into table_test (name,age) values ('vist',24) insert into <table>(<field>) values (<value>);Query data, for example:
select * from table_test select * from <table>;Modify data, for example:
update table_test set age=18 where name='vist' update <table> set <fidld>=<value> where <if>;Delete data, for example:
delete from table_test where name='vist' delete from <table> where <if>; node配置Need to install the mysql package
npm install mysqlnode
var mysql=require('mysql');var database='database_test';var table='table_test';Configure user password
var client=mysql.createConnection({ user: 'root', passowrd: '1234' });Connect to the database
client.connect();console.log('连接数据库');Use the database
client.query('use '+ database);Query operation
client.query('select * from '+ table , function(err, results, fields){ if(err){ throw err; } if(results){ console.log('查询'); results.map(function(item){ console.log('%s\t%d', item.name, item.age); }) } });Insertion operation
client.query('insert into '+ table + '(name, age) values (?, ?)', ['bestvist',20], function(err, results, fields){ if(err){ throw err; } if(results){ console.log('插入'); console.log(results); } });Update operation
client.query('update '+ table + ' set age=? where name=?',[18, 'bestvist'],function(err, results, fields){ if(err){ throw err; } if(results){ console.log('更新'); console.log(results); } });Delete operation
client.query('delete from '+ table +' where name=?', ['bestvist'], function(err, results, fields){ if(err){ throw err; } if(results){ console.log('删除'); console.log(results); } })Close database
client.end();I believe you have read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
Use JS to implement sorting algorithm
JS regular expressionHow to use
The above is the detailed content of How to implement node connection to mysql. For more information, please follow other related articles on the PHP Chinese website!