Nodejs for beginners to operate mysql
1: npm obtains the mysql package. Open cmd, cd to the nodejs installation directory, and run: npm install mysql. 2: nodejs code:
var http = require('http'),util = require('util'),mysql = require('mysql');http.createServer(function(req,res){res.writeHead(200,{'Content-type':'text/html'});var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'sanyue'});var sql = [ 'set names utf8;','create database if not exists nodejs;','use nodejs;','drop table if exists nodejs;','create table nodejs ( id int(4), name char(12), age int(2));','insert into nodejs values (1,"John",20),(2,"Tom",21);','select * from nodejs;' ];connection.query(sql[0],function(err,result,fields){if(err){res.write('Execute SQL: "'+sql[0]+'" failed!
');res.write(util.inspect(err,true));res.end();}else{res.write('Execute SQL: "'+sql[0]+'" successed!
');}});connection.query(sql[1],function(err,result,fields){if(err){res.write('Execute SQL: "'+sql[1]+'" failed!
');res.write(util.inspect(err,true));res.end();}else{res.write('Execute SQL: "'+sql[1]+'" successed!
');}});connection.query(sql[2],function(err,result,fields){if(err){res.write('Execute SQL: "'+sql[2]+'" failed!
');res.write(util.inspect(err,true));res.end();}else{res.write('Execute SQL: "'+sql[2]+'" successed!
');}});connection.query(sql[3],function(err,result,fields){if(err){res.write('Execute SQL: "'+sql[3]+'" failed!
');res.end();}else{res.write('Execute SQL: "'+sql[3]+'" successed!
');}});connection.query(sql[4],function(err,result,fields){if(err){res.write('Execute SQL: "'+sql[4]+'" failed!
');res.write(util.inspect(err,true));res.end();}else{res.write('Execute SQL: "'+sql[4]+'" successed!
');}});connection.query(sql[5],function(err,result,fields){if(err){res.write('Execute SQL: "'+sql[5]+'" failed!
');res.write(util.inspect(err,true));res.end();}else{res.write('Execute SQL: "'+sql[5]+'" successed!
');}});connection.query(sql[6],function(err,result,fields){if(err){res.write('Execute SQL: "'+sql[6]+'" failed!
');res.write(util.inspect(err,true));res.end();}else{res.write('Execute SQL: "'+sql[6]+'" successed!
');res.write('Result:
'+util.inspect(result,true)+'
');res.end();}});}).listen(9999);
3: running effect:
4: View mysql results: