node.js操作Mysql

MySql 驱动安装

定位到nodejs安装目录 cd C:\Program Files\nodejs

1 node --version //查看当前版本,用于判断nodejs是否安装成功

2 安装Mysql驱动:npm install mysql

3 查看已安装的驱动 npm list

4 查看已安装模块 npm search 模块名如:npm search mysql

编写脚本

1 查询

var mysql = require('mysql');

var connection = mysql.createConnection({

host : 'localhost',

user : 'root',

password : '123456',

database : 'ceshi'

});

connection.connect();

var sql = 'SELECT * FROM userinfo';

//查

connection.query(sql,function (err, result) {

if(err){

console.log('[SELECT ERROR] - ',err.message);

return;

}

console.log('--------------------------SELECT----------------------------');

console.log(result);

console.log('------------------------------------------------------------\n\n');

});

connection.end();

结果:

image

2 插入一条数据

var mysql = require('mysql');

var connection = mysql.createConnection({

host : 'localhost',

user : 'root',

password : '123456',

database : 'ceshi'

});

connection.connect();

//var sql = 'SELECT * FROM userinfo';

var sql = "INSERT INTO userinfo (NAME, age, sex)VALUES('小乖', 25, '男')";

//查

connection.query(sql,function (err, result) {

if(err){

console.log('[SELECT ERROR] - ',err.message);

return;

}

console.log('--------------------------SELECT----------------------------');

console.log(result);

console.log('------------------------------------------------------------\n\n');

});

connection.end();

结果:

image

你可能感兴趣的:(node.js操作Mysql)