本例中,创建了yoursql的数据库,yourtable的表格,表格列为id,tablecol1,tablecol2,并对表格数据进行的增删改查。
使用mysql
下载依赖:
npm install mysql --save
引入:
const mysql = require(‘mysql’)
创建数据库
1、手动创建数据库,例如库名:yoursql
2、代码创建数据库:
const dbInit = mysql.createConnection({
host:'localhost',
user:'root',
password:'xxxxxx', // 密码
})
const initsql = 'CREATE DATABASE yoursql' // 库名:yoursql
dbInit.query(initsql,(err,result) => {
if(err) throw err
console.log(result)
})
连接数据库
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'xxxxxxx', // 密码
database: 'yoursql'
})
查询数据库
数据库名:yoursql
const findSQL = `select * from information_schema.SCHEMATA where SCHEMA_NAME = 'yoursql'`;
db.query(findSQL, (err, result) => {
if (err) throw err;
console.log(result); // 没有返回空数组
}
查询表
数据库名:yoursql,表名:yourtable
const findTab = `select * from information_schema.TABLES t where t.TABLE_SCHEMA ='yoursql' and t.TABLE_NAME ='yourtable'`;
db.query(findTab, (err, result) => {
if (err) throw err;
console.log(result); // 没有返回空数组
}
创建表
表名:yourtable,设置id自增,并且id为主键
const creatTab = "create table yourtable(id int(11) NOT NULL AUTO_INCREMENT,tablecol1 VARCHAR(255),tablecol2 VARCHAR(255),PRIMARY KEY (id))"
db.query(creatTab, (err, result) => {
if (err) throw err
console.log(result)
})
新增数据
const addItem = `insert into yourtable set ?`;
const addData = {tablecol1: '内容1', tablecol2: '内容2'}
db.query(addItem, addData, (err, result) => {
if (err) throw err
console.log(result)
})
查询数据
1、查询表格全部数据
db.query(`select * from yourtable`, (err, result) => {
if (err) throw err
console.log(result)
})
2、查询表格特定数据
db.query(`select * from yourtable where tablecol1='内容1'`, (err, result) => {
if (err) throw err
console.log(result)
})
编辑数据
const yourId = 1; // 传参得到的id
const updateItem = `update yourtable set tablecol1='新内容1', tablecol2='新内容2' where id=${yourId}`;
db.query(updateItem, (err, result) => {
if (err) throw err
console.log(result)
})
删除数据
const yourId = 1; // 传参得到的id
db.query(`delete from yourtable where id=${yourId}`, (err, result) => {
if (err) throw err
console.log(result)
})