<h2>1.数据库</h2>
数据库命令:
mysql -u root -p //进入数据库
create database 库名; //创建数据库
show databases; //显示数据库
use 数据库名; //选择数据库
create table <表名> (<字段名1> <类型1> [,..<字段名n> <类型n>]) //创建数据表
<h2>2.JS文件</h2>
<h4>2.1 连接数据库</h4>
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost', //主机地址
user: 'root', //用户名
password: 'root', //密码
database: 'test', //数据库名
port: 3306 //端口号(默认3306)
});
connection.connect();
connection.query('SELECT 1+1 AS solution',function (error,results,fields) {
if(error) throw error;
console.log('the solution is:',results[0].solution);
});
<h4>2.2 添加数据</h4>
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
var addSql = 'INSERT INTO mytest(ID,name,sex) VALUES(0,?,?)';
var addSqlParams = ['aa', 'cc'];
connection.query(addSql, addSqlParams, function (err, result) {
if (err) {
console.log('err');
return;
}
console.log('INSERT ID:', result);
});
connection.end();
重新打开一个终端,运行 main.js 文件,如图所示,添加成功,然后查询数据库:
select * from mytest; //查询数据
<h4>2.3 删除数据</h4>
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
connection.query('DELETE FROM mytest where id=1',function (err,result) {
if(err){
console.log('err');
return
}
console.log('DELETE affectedRows',result.affectedRows);
})
connection.end();
运行文件,打开数据库查询结果:
<h4>2.4 修改数据</h4>
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
connection.query('UPDATE mytest SET name=? where id=2','change',function (err,result) {
if(err){
console.log(err);
return
}
console.log('update affectedRows:',result.affectedRows);
});
connection.end();
运行文件,查看结果:
<h4>2.5 查看数据 </h4>
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
connection.query('select * from mytest',function (err,result) {
if(err){
console.log('err');
}
console.log(result)
});
connection.end();
运行文件,查看结果: