首页 🚓JavaScript

node连接数据库

准备工作

1.再vscode中新建文件夹,右键文件夹选择集成终端中打开

2.输入初始化命令:npm init -y

3.安装express 模块:npm i express

4.安装mysql模块:npm i mysql

image-20211012120243184

编写代码

创建index.js

var mysql = require('mysql');
var connection = mysql.createConnection({
  user: 'root', //用户名
  password: 'admin', //密码
  host: 'localhost', //主机(默认都是local host)
  database: 'user', //数据库名
});

connection.connect(function (err) {
  if (err) {
    console.log('链接失败');
    throw err;
  } else {
    console.log('链接成功');
  }
  //新建数据库
  let createSql = 'CREATE TABLE users(id INT UNSIGNED AUTO_INCREMENT,user varchar(255) NOT NULL,age INT(11) NOT NULL,sex varchar(16),PRIMARY KEY(id))';
  let values = [
    ['小红', 18, '女'],
    ['小白', 19, '女'],
    ['小丽', 20, '女'],
    ['小李', 21, '女'],
    ['小绿', 22, '女'],
    ['小紫', 23, '女'],
    ['小丽', 24, '女'],
  ];
  //插入数据
  let addSql = 'INSERT INTO users(user,age,sex) VALUES ?';
  //查询数据
  let querySql = 'select * from users';
  //更改数据
  let updataSql = 'UPDATE  user set id =5,user="小李",password="12345678",email="168qq.com"';
  //删除数据
  let delSql = 'DELETE FROM user';
  connection.query(querySql, function (err, result) {
    if (err) {
      console.log('[INSERT ERROR] - ', err.message);
      return;
    }

    console.log('--------------------------INSERT----------------------------');
    console.log(result);
    console.log('-----------------------------------------------------------------\n\n');
  });
});运行 

image-20211012120920577




文章评论

目录