欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

nodejs 操作mysql

程序员文章站 2022-07-10 16:10:36
...

1、安装mysql模块

2、新建mysql连接

const mysql = require('mysql');

const connection = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: '12345678',
   database: 'test'
});

connection.connect(function(){
    console.log('connect success')
});

3、执行查询语句

const mysql = require('mysql');

const connection = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: '12345678',
   database: 'test'
});

connection.connect(function(){
    console.log('connect success')
});

connection.query("select * from users", function(err, result, fields){
    if(err) throw err;
    for(let i = 0; i < result.length; i++){
        console.log('名称:' + result[i].username);
        console.log('密码:' + result[i].password);
    }
});

connection.end();

nodejs 操作mysql

nodejs 操作mysql

4、插入数据

const insertSql = 'insert into users (username, password) values (?, ?)';
const sqlParam = ['白骨精', '123456'];

connection.query(insertSql, sqlParam, function(err, result){
    if(err)throw err;
    console.log('insert success');
    console.log(JSON.stringify(result));
});

nodejs 操作mysql

 

5、删除数据

connection.query("delete from users where id = ?", [6], function(err, result){
    if(err)throw err;
    console.log('delete success');
});

 

nodejs 操作mysql

 

6、更新数据

connection.query("update users set password = ? where id = ?", ['wang', 3], function(err, result){
   if(err) throw err;
   console.log('更新成功');
});

 

nodejs 操作mysql

 

 

 

 

 

 

相关标签: nodejs