浅谈node连接mysql数据库的方法


本文摘自PHP中文网,作者青灯夜游,侵删。

本篇文章和大家聊聊node连接mysql数据库的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

相关推荐:《node js教程》

node使用原生方式,连接mysql数据库

1.png

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

(async () => {

    // 链接数据库

    const mysql = require('mysql2/promise');    // npm i mysql2

    const cfg = {

        host: 'localhost',

        user: 'root',

        password: ';he%0f_,ljyW',

        database: 'izengx',

    }

    const connection = await mysql.createConnection(cfg);

     

    // 创建一个新表tests

    let ret = await connection.execute(`CREATE TABLE IF NOT EXISTS tests (

        id INT NOT NULL AUTO_INCREMENT,

        message VARCHAR(45) NULL,

        PRIMARY KEY (id)

    )`)

    console.log('create', ret);

     

    // 新建数据

    ret = await connection.execute(`INSERT INTO tests(message) VALUE(?)`, ['newData'])

    console.log('新建数据', ret);

     

    const [rows, fields] = await connection.execute(`

        SELECT * FROM tests

    `)

    console.log('查询数据', rows);

     

})()

使用数据库中间件(ORM):sequelize连接和操作数据库

阅读剩余部分

相关阅读 >>

node.js真的单线程吗?进程间如何通信?

如何使用ppa在ubuntu上安装最新的node.js和npm

如何使用node.js读取json文件

详解主动终止node.js进程的几种方法

深入了解node.js中的express框架

linux服务器搭建node.js环境的步骤介绍

node.js底层是什么语言

mac下更新node.js到最新版

了解node.js中的process对象

exports和module.expors之间有什么区别及联系?

更多相关阅读请进入《node.js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...