使用node js 操作 Mysql 数据库
//node js 数据库操作 MySQL //使用https://github.com/felixge/node-mysql //sql 操作 http://www.w3school.com.cn/sql/ //http://see.xidian.edu.cn/cpp/html/1441.html /** 建立数据库连接 */ var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database : 'jkkDB' //在下面创建数据库之后,添加此字段,连接对应的库 }); connection.connect(); //测试数据库连接 connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); //2 表示连接成功 }); /* //建立 数据库 jkkDB var createDataBase = 'CREATE DATABASE jkkDB'; connection.query(createDataBase, function (err0, res0) { if (err0) console.log(err0); console.log("create DataBase ==> "); console.log(res0); }); */ /* //创建表 var createTable = 'CREATE TABLE jkkTable(name char,age int)'; connection.query(createTable, function (err0, res0) { if (err0) console.log(err0); console.log("create Table ==> "); console.log(res0); }); */ /* //插入一条数据 var insertSql = "insert into jkkTable values('JKK',24),('zyk',18), ('YK',8);"; connection.query(insertSql, function (err0, res0) { if (err0) console.log(err0); console.log("insert row ==> "); console.log(res0); }); */ /** //更新表数据 */ var updateSql = "update jkkTable set age=20 where name='J';"; connection.query(updateSql, function (err0, res0) { if (err0) console.log(err0); console.log("update row ==> "); console.log(res0); }); //查询 var selectStr = 'select * from jkkTable'; connection.query(selectStr, function (err0, rows) { if (err0) console.log(err0); console.log("select row ==> "); console.log(rows); for (var i in rows) { console.log(rows[i]); } }); //关闭数据库连接; connection.end();
(责任编辑:IT) |