MySQL与SQLite3数据库的入门指南

807 阅读3分钟

MySQL数据库

MySQL是一种关系型数据库,有一套强制性的规则和原则,这些规则确保了数据的结构化、完整性和一致性。

启动数据库服务:win+r打开"运行"对话框,输入services.msc,找到MySQL将其启动。 image.png

在vscode中下载mysql插件,然后左边就会多出一个数据库,如下; image.png

输入密码建立连接:

image.png

然后再创建表 image.png

然后就是把数据库中的数据打印在控制台上。

初始化项目 image.png

启动web服务,可以看到打印hello world。

const http = require('http')
const mysql = require('mysql2');

const server = http.createServer((req, res) => {
  res.end('hello world')
})

server.listen(3000, () => {
  console.log('Server is running on port 3000')
})

525480c5f6bf1eaaed554835e958d36.png

接下来就是连接数据库

const http = require('http')
const mysql = require('mysql2');

const server = http.createServer((req, res) => {
  if (req.url == '/users') {    // 处理对`/users`路径的请求
    // 连接数据库,并将数据库中的数据读取到返回前端
    const connection = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      database: 'demo',
      password: '123456'
    });
    connection.query(
      'SELECT * FROM users',
      function (err, results, fields) {
        console.log(results); // results contains rows returned by server
      }
    );
  }
  res.end('hello world')
})

server.listen(3000, () => {
  console.log('Server is running on port 3000')
})

这段代码将在你访问http://localhost:3000/users时,从数据库中检索users表的数据,并将其打印到控制台,如下。

image.png

SQLite3数据库

sqlite3 是一个开源的嵌入式关系型数据库,它的使用完全集成在一个文件里,不需要任何配置,sqlite3 不是一个单独的服务进程,而是嵌入在应用程序中的,非常适合作为轻量型应用的存储方案。

在vscode中下载插件 image.png

使用 npm install sqlite3 命令可以安装 sqlite3 包。这个过程不仅会安装 sqlite3 的 npm 包,还会安装 sqlite 数据库。

image.png

// 姓名、年龄、工资、部门
const sqlite3 = require('sqlite3');    // 引入 sqlite3 模块

// 创建数据库并连接
const connection = new sqlite3.Database('./mydatabase.db', (err) => {
  if (err) {
    console.log('连接失败');
    return
  }

  console.log('连接成功');
  // 创建表格
  connection.run(`
    CREATE TABLE IF NOT EXISTS employees (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      age INTEGER NOT NULL,
      salary REAL NOT NULL,
      department TEXT NOT NULL
    )
  `)
})

运行该代码,连接成功后就会创建一个mydatabase.db的文件,且会在里面创建一个名为employees的表,如下。 image.png

image.png

总的来说,MySQL是一个关系型数据库管理系统,通常用作Web应用程序的后端存储,通常适用于大型、中小型以及需要多用户并发访问的应用程序。而SQLite也是一个关系型数据库管理系统,但它是轻量级的,无服务器的,直接读写普通的磁盘文件。好了,关于MySQL和SQLite3数据库的使用和配置讲到这里了。